Wysiwyg button with form #4

Welcome to the second article in my tutorial about building a wysiwyg button for drupal 7 which enables use to inserting tokens.

This will be a four step tutorial

  1. Step one will be building the module and a simple wysiwyg button
  2. Step two will cover a simple wysiwyg button
  3. Step three will expand the button with a multi field form
  4. Step four will make this form dynamic with ajax callbacks for removing and adding fields

This next part will cover how to expand the form to use ajax for dynamic adding and removing fields.

I followed this exellent article about how to implement det dynamic adding and removing fields, but since we are using jquery ajax to load our for we don't have the luxury of drupals ajax to ensure ajax handling for our form and we need to add this in.

/**
 * Insert token form
 */
function example_insert_form($form, &$form_state) {
  drupal_add_library('system', 'ui.dialog');
  $form['#tree'] = TRUE;
  if (empty($form_state['num_objects'])) {
    $form_state['num_objects'] = 1;
  }
  $ids = null;
  $args = $form_state['build_info']['args'];
  if(isset($args[0])) {
    $ids = explode(',', $args[0]);
    if($form_state['num_objects'] == 1) {
      $form_state['num_objects'] = count($ids);
    }
  }
  $form['objects'] = array(
    '#type' => 'fieldset',
    '#title' => t('Objects'),
    '#prefix' => '<div id="example-fieldset-wrapper">',
    '#suffix' => '</div>',
  );
 
  for($i = 0; $i < $form_state['num_objects']; $i++) {
    $form['objects'][$i]['object'] = array(
      '#type' => 'textfield',
      '#title' => t('Entity id'),
      '#prefix' => '<div class="col1">',
      '#suffix' => '</div>',
      '#default_value' => isset($form_state['values'][$i]) ? $form_state['values'][$i]['object'] : '',
    );
    if(isset($ids[$i])) {
      $form['objects'][$i]['object']['#default_value'] = $ids[$i];
    }
  }
 
  $form['objects']['add_item'] = array(
    '#type' => 'submit',
    '#value' => t('Add another'),
    '#submit' => array('example_add_more_add_one'),
    // See the examples in ajax_example.module for more details on the
    // properties of #ajax.
    '#ajax' => array(
      'callback' => 'example_add_more_callback',
      'wrapper' => 'example-fieldset-wrapper',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
  if ($form_state['num_objects'] > 1) {
    $form['objects']['remove_item'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('example_add_more_remove_one'),
      '#ajax' => array(
        'callback' => 'example_add_more_callback',
        'wrapper' => 'example-fieldset-wrapper',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#attributes' => array(
      'class' => array('form-save-ids'),
    ),
  );

  return $form;
}

/**
 * Callback for both ajax-enabled buttons.
 *
 * Selects and returns the fieldset with the names in it.
 */
function example_add_more_callback($form, $form_state) {
  return $form['objects'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function example_add_more_add_one($form, &$form_state) {
  $form_state['num_objects']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function example_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_objects'] > 1) {
    $form_state['num_objects']--;
  }
  $form_state['rebuild'] = TRUE;
}

As you can see we are using a simple count setting to increase or decrease the number of text fields in the form. This works fine for our simple form and we just need to add a few changes to the js in order to forward this change from the client to the backend. So make the following change to the insert_form function:

  insert_form: function (data, settings, instanceId) {
    // Location, where to fetch the dialog.
    var aurl = Drupal.settings.basePath + 'example/insert/ajax';
    if(settings.ids) {
      aurl += '/' + settings.ids.join();
    }
    var dialogdiv = $('<div id="example-insert-dialog"></div>');
    dialogdiv.load(aurl, function(){
      var dialogClose = function () {
        try {
          dialogdiv.dialog('destroy').remove();
        } catch (e) {};
      };

Now that we have this in place we need to expand our menu so we can send the id variables to the form.

/**
 * implements hook_menu
 */
function example_menu() {
  $items = array();
  $items['example/insert/nojs'] = array(
    'page callback' => 'example_get_insert_form',
    'page arguments' => array(2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items['example/insert/ajax'] = array(
    'delivery callback' => 'ajax_deliver'
  ) + $items['example/insert/nojs'];
 
  $items['example/insert/nojs/%'] = array(
    'page callback' => 'example_get_insert_form',
    'page arguments' => array(2, 3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items['example/insert/ajax/%'] = array(
    'delivery callback' => 'ajax_deliver'
  ) + $items['example/insert/nojs/%'];
  return $items;
}

If you implement this, you will find that the ajax callbacks aren't exactly using ajax yet. This is because as I said we don't have the luxury of drupals ajax handing when we are using the jquery ajax load function. In order to fix this we need to make a few changed to the ajax get form function so we compile the scripts and add then to the data being returned.

/**
 * Retrive the insert form.
 */
function example_get_insert_form($ajax, $ids = '') {
  $is_ajax = $ajax === 'ajax';
  $form = drupal_get_form('example_insert_form', $ids);
  if ($is_ajax) {
    $form = drupal_render($form);
    // Generate the settings:
    $settings = '';
    $javascript = drupal_add_js();
    if(isset($javascript['settings'], $javascript['settings']['data'])) {
      $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
      $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $javascript['settings']['data']));
      $settings .=  ');</script>';
    }
    die($form . $settings);
  }
  else {
    return $form;
  }
}

Now that this is done, the form uses ajax to add or remove fields to the form and it keeps the already entered data while doing to.

I hope this helps and if you have any questions let me now. For a working version of this see ting_object