back

Knowlegde

Knowledge Centre

Replace a field's content based on another field using AJAX

by editor | 08.08.2019

Replace a field's content based on another field using AJAX

PROBLEM/MOTIVATION

I was given the situation where a field of a Content Type had to be updated on real time based on the value of the Title field, concatenated with some text.

More specific, you would generate a subdomain based on your desired site name + our domain name.

 

SEE IT IN ACTION HERE: HTTPS://WWW.SCREENCAST.COM/T/9N2NNQCJVX

The Title field represent the desired name

The Subdomain field will be updated with the value of the Title concatenated with '.subdomain.com'

 

THE SOLUTION

In order to implement this we will add an AJAX callback event to our Title field.

 

First of all , in our custom module’s .module file we will need to declare that we will be using 3 classes/interfaces in our code.

 

article.png
Top
default
use Drupal\Core\Form\FormStateInterface;

use Drupal\Core\Ajax\AjaxResponse;

use Drupal\Core\Ajax\InvokeCommand;

 

Then we will implement the hook hook_form_alter() (see more here).

 

/**
 * Implements hook_form_alter().
 */
function drupal_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['title']['widget'][0]['value']['#ajax'] =
      [
        // Our callback function.
        'callback' => 'updateSubdomain',

        // Is set false, because we might want to make changes multiple times.
        'disable-refocus' => FALSE,

        // The JS event to trigger on; similar to 'onchange'.
        'event' => 'change',

        // The id of the element you wish to change, # is not required;
        // you can get the ID by inspecting the element.
        'wrapper' => 'edit-field-subdomain-0-value',
      ];
}

 

Now we will implement the callback function: 

 

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @return \Drupal\Core\Ajax\AjaxResponse
 */
function updateSubdomain(&$form, FormStateInterface $form_state) {      
  if (!empty($form_state->getValue('title')[0]['value'])) {

    // Get the value of the title and concatenate it.
    $title = $form_state->getValue('title')[0]['value'] . '.subdomain.com';

    // Instantiate a new ajax response object.
    $response = new AjaxResponse();

    // Will invoke the jQuery method .val() https://api.jquery.com/val/
    $response->addCommand(new InvokeCommand('#edit-field-subdomain-0-value', 'val', [$title]));

    // Return the AJAX response.
    return $response;
  }

}

 

The function InvokeCommand accepts the following parameters:

 

InvokeCommand($selector, $method, array $arguments = []) {}

 

String $selector - the Jquery selector, in our case the id

String $method - the Jquey method to invoke

array $arguments - arguments to pass to the method, in our case the new value.

 

FULL CODE HERE

 

<?php

/**
 * @file
 * Contains drupal.module.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;

/**
 * Implements hook_form_alter().
 */
function drupal_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['title']['widget'][0]['value']['#ajax'] =
      [
        'callback' => 'updateSubdomain',
        'disable-refocus' => FALSE,
        'event' => 'change',
        'wrapper' => 'edit-field-subdomain-0-value',
      ];
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @return \Drupal\Core\Ajax\AjaxResponse
 */
function updateSubdomain(&$form, FormStateInterface $form_state) {
  if (!empty($form_state->getValue('title')[0]['value'])) {
    $title = $form_state->getValue('title')[0]['value'] . '.subdomain.com';
    $response = new AjaxResponse();
    $response->addCommand(new InvokeCommand('#edit-field-subdomain-0-value', 'val', [$title]));
    return $response;
  }
}

 

Tell us in comments if the above approach has been useful to you and what other alternatives you would use in such a case.

  • Knowlegde
    Knowledge Centre
    admin
  • Knowlegde
    Knowledge Centre
    Port your sites to Drupal 9
    editor
  • Knowlegde
    Knowledge Centre
    Drupal 8 or Drupal 9
    editor

Post a Comment.