Search code examples
phpajaxdrupal-7

Drupal 7 add ajax listener directly to node form


I'm trying to register an ajax listener to a checkbox on one of my standard node forms. I want to display certain regions of the form only in case, the field is checked. I can get the drupal ajax ecosystem to work, when I use it in a custom form, but I'm unable to make it work on my node forms.

First I hook into form_alter to check if I'm with the node type I want to add the listener for:

function interceptor_form_alter(&$form, &$form_state, $form_id) {
  if($form_id === 'film_node_form') {
    interceptor_dvd_listener($form, $form_state);
  }
}

Then I try to attach the ajax stuff to my checkbox, which name is field_dvd:

function interceptor_dvd_listener(&$form, &$form_state) {
  $form['field_dvd'] = array(
    '#title' => t('You want to display DVD informations too?'),
    '#type' => 'checkbox',
    '#ajax' => array(
      'callback' => 'interceptor_dvd_listener_callback',
      'wrapper' => 'checkboxes-div',
      'effect' => 'slide',
      'progress' => array('type' => 'none'),
    ),
  );
  return $form;
}

The function interceptor_dvd_listener_callback is never called. I try to print some debug information there, but nothing happens...

function interceptor_dvd_listener_callback($form, $form_state) {
  data_service_log_object($form);
}

UPDATE

After passing the form variable as reference to interceptor_dvd_listener the ajax callback worked like expected.


Solution

  • Most likely error:

    You are not passing $form by reference to interceptor_dvd_listener() function. You are also not using the returned value from this function. Change the function definition to:

    function interceptor_dvd_listener(&$form, &$form_state) {
      $form['field_dvd'] = array(
        '#title' => t('You want to display DVD informations too?'),
        '#type' => 'checkbox',
        '#ajax' => array(
          'callback' => 'interceptor_dvd_listener_callback',
          'wrapper' => 'checkboxes-div',
          'effect' => 'slide',
          'progress' => array('type' => 'none'),
        ),
      );
    }
    

    Now see if it works. If it doesn't then, do the following:

    1. Make sure that your custom module name is "interceptor".
    2. Make sure that the id of the form you are modifying is "film_node_form".
    3. Change the function interceptor_form_alter() to:

      function interceptor_form_alter(&$form, &$form_state, $form_id) {
        if($form_id == 'film_node_form') {
          interceptor_dvd_listener($form, $form_state);
        }
      }
      

    If it still doesn't work, print out $form variable at the end of interceptor_form_alter() function and see if field_dvd has the #ajax key.

    You could also use this module (https://www.drupal.org/project/field-conditional-state) instead of writing all this custom code.