Skip to main content
2 of 4
Added more details to the question.

Attach an #ajax callback to a field when the form is reloading from previous ajax request

Is it possible to attach an #ajax callback to a field when the form is being regenerated from a previous ajax event (like a submit button)?


What I tried

Adding the #ajax callback to the field when the form is reloading does not seems to trigger anything:

$form['my_field'] = array(
  '#type' => 'radios',
  '#title' => t('Vous souhaitez ?'),
  '#required' => TRUE,
  '#options' => array(
    'devis' => t('Un devis gratuit'),
    'rappel' => t('Etre rappelé'), 
    'contact' => t('Entrer en contact')
  ),
);
// Adding the ajax event to the field.
$form['my_field']['#ajax'] = array(
  'wrapper' => 'module_form',
  'callback' => 'module_form_ajax_callback',
);

The Drupal.settings array is not updated after the end of the ajax process. Seems like I'm trying to do something the Form API isn't able to do out of the box... Here's the result of the first ajax request: result of the first ajax request You can see there's still only the submit button in the form attached to an ajax event.

I tried updating Drupal.settings "manually" with ['#attached']['js'] like this:

$form['my_field']['#attached']['js'][] = array(
    'data' => array('ajax' => array(
      $field['#id'] => array(
        'wrapper' => 'module_form',
        'callback' => 'module_form_ajax_callback',
        'event' => 'change',
        'url' => '/system/ajax',
        'submit' => array(
          '_triggering_element_name' => $field['#name'],
          'form_build_id' => $form_state['complete form']['#build_id'],
        )
      )
    )),
    'type' => 'setting',
  );
  

Like that, the Drupal.settings array isn't updated visually (no change when checking source code with Chrome Dev Tool) but changes have happened somewhere since an ajax request is launched when I change the value of the field (a "radio" field).

Here's the response:

[{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"matelem","theme_token":"sSBaD0iETb4hcF3d4oLI3owEByI1rlhng80cbpQvEj0"},"merge":true}]

Looks like nothing of value is returned, an ajax call have been made but Drupal doesn't seem to understand what I'm asking of him.

Anyway, trying to define values manually for Drupal.settings is too much of a hassle. Things like "event" should be set automatically based on the type of the field but it needs to be set "by hand" when using ['#attached']['js']... Feels like I'm missing something.

Any idea?