0

I'm implementing an ajax callback function whats the issue with my code not returning anything. I'm new to backend

  <?php
use Drupal\node\Entity\Node;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Query\QueryFactory;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

/**
 * Implements hook_form_alter().
 */
function hook_form_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'webform_submission_go_to_csv_import_add_form') {
    // Choose for "Featured Type" field "N/A" value by default.
    $form['elements']['name']= [
      '#type' => textfield,
      '#title' => 'sammy',
      '#ajax' => [
                'callback' => '::some_ajax_sample',
                'wrapper' => 'edit-name',
                'event' => 'keyup',
                'progress' => [
                  'type' => 'throbber',
                  'message' => 'loading.....',
                ]
              ],
            ];


  }
}

function some_ajax_sample(array &$form, FormStateInterface $form_state) {

  $response = new Response($form['elements']['name']['#title'] = 'Test');
    return $response;
   }

1 Answer 1

3

there are a few things that could go wrong with this. Ajax callbacks can be a really hard thing to do and often requires a bit of trail and error. Hope this helps.

First of all, when your ajax callback function should not contain the "::".
This is only used when you are programming inside a Class, right now you're in a .module.
So you can change to.

'callback' => 'some_ajax_sample'

Furthermore you should check with a breakpoint if you even get inside the function. This should be resolved when removing the ::.

Second thing you should do is add the wrapper div to your element.
You can do it like this:

$form['elements']['name']= [
  '#prefix' => '<div id="edit-name">'
  '#suffix' => '</div>'
  '#type' => textfield,
  '#title' => 'sammy',
  '#ajax' => [
            'callback' => 'some_ajax_sample',
            'wrapper' => 'edit-name',
            'event' => 'keyup',
            'progress' => [
              'type' => 'throbber',
              'message' => 'loading.....',
            ]
          ],
        ];
}

When you added the wrapper, Drupal knows which element should be replaced and update.

Last thing you can try is to remove the response and to just return the $form['elements']['name'].

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.