Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

in this tuto, I'll show you how to add Ajax triggers to a form in drupal 8 by adding the #ajax property like the example in below: 

create codimth_form_api.routing.yml

codimth.form_api:
  path: '/codimth-simple-form'
  defaults:
    _form:  '\Drupal\codimth_form_api\Form\CodimthSimpleForm'
    _title: 'AJAX form trigger JS callback'
  requirements:
    _permission: 'access content'

create src/Form/CodimthSimpleForm.php

<?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;


/**
 * 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) {
    $response = new AjaxResponse();
    $response->addCommand(
      new HtmlCommand(
        '.result_message',
        '<div class="my_message">' . $this->t('The result is @result', ['@result' => strtoupper($form_state->getValue('name')) ])
      )
    );
    return $response;
  }

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

As you can see from this example, the #ajax property for a form element is an array. Here are the details of its elements, all of which are optional:

  • callback: The callback to invoke to handle the server side of the Ajax event. More information on callbacks is below in "Setting up a callback to process Ajax".
  • wrapper: The HTML 'id' attribute of the area where the content returned by the callback should be placed. Note that callbacks have a choice of returning content or JavaScript commands; 'wrapper' is used for content returns.
  • method: The jQuery method for placing the new content (used with 'wrapper'). Valid options are 'replaceWith' (default), 'append', 'prepend', 'before', 'after', or 'html'. See http://api.jquery.com/category/manipulation/ for more information on these methods.
  • effect: The jQuery effect to use when placing the new HTML (used with 'wrapper'). Valid options are 'none' (default), 'slide', or 'fade'.
  • speed: The effect speed to use (used with 'effect' and 'wrapper'). Valid options are 'slow' (default), 'fast', or the number of milliseconds the effect should run.
  • event: The JavaScript event to respond to. This is selected automatically for the type of form element; provide a value to override the default.
  • prevent: A JavaScript event to prevent when the event is triggered. For example, if you use event 'mousedown' on a button, you might want to prevent 'click' events from also being triggered.
  • progress: An array indicating how to show Ajax processing progress. Can contain one or more of these elements:
    • type: Type of indicator: 'throbber' (default) or 'bar'.
    • message: Translated message to display.
    • url: For a bar progress indicator, URL path for determining progress.
    • interval: For a bar progress indicator, how often to update it.
  • url: A \Drupal\Core\Url to which to submit the Ajax request. If omitted, defaults to either the same URL as the form or link destination is for someone with JavaScript disabled, or a slightly modified version (e.g., with a query parameter added, removed, or changed) of that URL if necessary to support Drupal's content negotiation. It is recommended to omit this key and use Drupal's content negotiation rather than using substantially different URLs between Ajax and non-Ajax.

To return commands, you need to set up an object of class \Drupal\Core\Ajax\AjaxResponse, and then use its addCommand() method to add individual commands to it.

HtmlCommand: AJAX command for calling the jQuery html() method.

The 'insert/html' command instructs the client to use jQuery's html() method to set the HTML content of each element matched by the given selector while leaving the outer tags intact.
$response->addCommand(new HtmlCommand($Selector,$content,$settings));

the result:

before submit

ajax example in drupal 8

after submit

ajax example in drupal 8

 

 

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon