Sunday, January 8, 2017

Create custom ajax command

Drupal 7 offers a lot of default ajax commands which are the part of Drupal Ajax Framework. Furthermore, ctools module extends a set of ajax commands and provides own commands. But what if you need some specific command? First, you need to write a wrapper function which returns ajax command array. Should looks like this one:
<?php

/**
 * Ajax command for rendering canvas data.
 *
 * @param array $data
 *   Settings array.
 *
 * @param mixed $some_other_parameter
 *   Some other parameter.
 *
 * @return array
 *   Ajax command array.
 */
function specific_ajax_command(array $data, $some_other_parameter) {
  return [
    // Name of a js function.
    'command' => 'specificAjaxCommand',

    // Data will be available in js function.
    'specific_data' => $data,

    // You can define as many parameters
    // for your command as you want.
    'some_other_parameter' => $some_other_parameter,
  ];
}
Second step is js command function implementation :
(function ($) {
  'use strict';

  // Ensure that Drupal.ajax object is set up.
  if (Drupal.ajax) {
    Drupal.ajax.prototype.commands.specificAjaxCommand = function (ajax, response, status) {
      // Check response status.
      if (status == 'success') {
        // Get data from back-end side.
        var specificData = response.specific_data,
            someOtherParameter = response.some_other_parameter;
        
        // Perform specific actions dependent on a data.
      }
    };
  }

}(jQuery));
Third, ensure that js file contains code above is added to a page before returning ajax command. When it's done you are ready to go with a new ajax command:
<?php

/**
 * Ajax page callback.
 *
 * @return array
 *   Array contains Drupal ajax commands.
 */
function module_ajax_page_callback() {
  $some_data = [];
  $some_other_parameter = 'Some other parameter value';
  $commands[] = specific_ajax_command($some_data, $some_other_parameter);
 
  return [
    '#type' => 'ajax',
    '#commands' => $commands,
  ];
}

Key notes:

No comments:

Post a Comment