Skip to main content
Category:

Drupal 8 provides the option to include an Ajax Callback within our applications using the Ajax Framework, Drupal has many AJAX Callback Commands in core like AddCssCommand, HtmlCommand, ...

in this tuto, I'll show you how to create custom ajax command. let's create custom module "example":

create example.info.yml file:

name: 'example'
type: module
description: 'My Awesome Module'
core: 8.x
package: 'Custom'

create example.libraries.yml file:

example-library:
  js:
    js/example.js: {}
  dependencies:
    - core/drupal.ajax

create example.module file:

I want to attach this library to a specific form. So, we’ll define a form alter:

<?php

/**
 * @file
 * Contains example.module.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function example_help($route_name, RouteMatchInterface $route_match)
{
  switch ($route_name) {
    // Main module help for the example module.
    case 'help.page.example':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('My Awesome Module') . '</p>';
      return $output;

    default:
  }
}


function example_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
  if ($form_id == 'codimth_form_api_ajax_demo') {
    $form['#attached']['library'][] = "example/example-library";
  }
}

 

create js/example.js file:

(function ($, Drupal) {
  Drupal.AjaxCommands.prototype.example = function (ajax, response, status) {
    alert(response.message);
  }

})(jQuery, Drupal);

to get message variable, juste use response.message.

create src/Ajax/ExampleCommand.php file:

<?php

namespace Drupal\example\Ajax;

use Drupal\Core\Ajax\CommandInterface;

/**
 * Class ExampleCommand.
 */
class ExampleCommand implements CommandInterface {

  protected $message;

  public function __construct($message) {
    $this->message = $message;
  }

  /**
   * Render custom ajax command.
   *
   * @return ajax
   *   Command function.
   */
  public function render() {
    return [
      'command' => 'example',
      'message' => $this->message,
    ];
  }

}

render(): return a render array. In this case, 'example' is the javascript command which I used inside the example.js file(Drupal.AjaxCommands.prototype.example).

We can define other properties on this response, for example a custom message.

Invoking our custom command:

To add our command, we need to tell Drupal to only return AJAX content, rather than a full web page. In this custom form submit function, I create a new AjaxResponse and call the addCommand() method to add our custom command.

<?php

namespace Drupal\codimth_form_api\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\example\Ajax\ExampleCommand;


/**
 * Class CodimthSimpleForm
 * @package Drupal\codimth_form_api\Form
 */
class CodimthSimpleForm extends FormBase
{
  /**
   * {@inheritdoc}
   */
  public function getFormId()
  {
    return 'codimth_form_api_ajax_demo';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state)
  {

    $form['uppercase_name'] = [
      '#type' => 'markup',
      '#markup' => '<div class="result_message"></div>',
    ];

    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
    ];

    $form['actions'] = [
      '#type' => 'button',
      '#value' => $this->t('Uppercase Name'),
      '#ajax' => [
        'callback' => '::uppercaseName',
        'progress' => array(
          'type' => 'throbber',
          'message' => 'in progress ...',
        ),
      ],
    ];
    return $form;
  }

  /**
   * @param array $form
   * @param FormStateInterface $form_state
   * @return AjaxResponse
   */
  public function uppercaseName(array $form, FormStateInterface $form_state)
  {
    $message = 'The result is '.strtoupper($form_state->getValue('name'));
    $response = new AjaxResponse();
    $response->addCommand(
      new ExampleCommand($message)
    );
    return $response;
  }

  /**
   * @param array $form
   * @param FormStateInterface $form_state
   */
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
  }
}

 

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook