Skip to content

Instantly share code, notes, and snippets.

@AkshayKalose
Last active November 23, 2022 13:40
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save AkshayKalose/37df41d94d16ee1eec35 to your computer and use it in GitHub Desktop.
Save AkshayKalose/37df41d94d16ee1eec35 to your computer and use it in GitHub Desktop.
Drupal 8 - Ajax Example
name: 'Ajax Example'
description: 'Just an Ajax Example'
core: 8.x
type: module
ajax_example.form:
path: '/admin/ajax_example'
defaults:
_form: 'Drupal\ajax_example\Form\AjaxExampleForm'
_title: 'Ajax Example'
requirements:
_permission: 'access administration pages'
<?php
/**
* @file
* Contains Drupal\ajax_example\AjaxExampleForm
*/
namespace Drupal\ajax_example\Form;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ChangedCommand;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class AjaxExampleForm extends FormBase {
public function getFormId() {
return 'ajax_example_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['user_name'] = array(
'#type' => 'textfield',
'#title' => 'Username',
'#description' => 'Please enter in a username',
'#ajax' => array(
// Function to call when event on form element triggered.
'callback' => 'Drupal\ajax_example\Form\AjaxExampleForm::usernameValidateCallback',
// Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
'effect' => 'fade',
// Javascript event to trigger Ajax. Currently for: 'onchange'.
'event' => 'change',
'progress' => array(
// Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
'type' => 'throbber',
// Message to show along progress graphic. Default: 'Please wait...'.
'message' => NULL,
),
),
);
$form['random_user'] = array(
'#type' => 'button',
'#value' => 'Random Username',
'#ajax' => array(
'callback' => 'Drupal\ajax_example\Form\AjaxExampleForm::randomUsernameCallback',
'event' => 'click',
'progress' => array(
'type' => 'throbber',
'message' => 'Getting Random Username',
),
),
);
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
drupal_set_message('Nothing Submitted. Just an Example.');
}
public function usernameValidateCallback(array &$form, FormStateInterface $form_state) {
// Instantiate an AjaxResponse Object to return.
$ajax_response = new AjaxResponse();
// Check if Username exists and is not Anonymous User ('').
if (user_load_by_name($form_state->getValue('user_name')) && $form_state->getValue('user_name') != false) {
$text = 'User Found';
$color = 'green';
} else {
$text = 'No User Found';
$color = 'red';
}
// Add a command to execute on form, jQuery .html() replaces content between tags.
// In this case, we replace the desription with wheter the username was found or not.
$ajax_response->addCommand(new HtmlCommand('#edit-user-name--description', $text));
// CssCommand did not work.
//$ajax_response->addCommand(new CssCommand('#edit-user-name--description', array('color', $color)));
// Add a command, InvokeCommand, which allows for custom jQuery commands.
// In this case, we alter the color of the description.
$ajax_response->addCommand(new InvokeCommand('#edit-user-name--description', 'css', array('color', $color)));
// Return the AjaxResponse Object.
return $ajax_response;
}
public function randomUsernameCallback(array &$form, FormStateInterface $form_state) {
// Get all User Entities.
$all_users = entity_load_multiple('user');
// Remove Anonymous User.
array_shift($all_users);
// Pick Random User.
$random_user = $all_users[array_rand($all_users)];
// Instantiate an AjaxResponse Object to return.
$ajax_response = new AjaxResponse();
// ValCommand does not exist, so we can use InvokeCommand.
$ajax_response->addCommand(new InvokeCommand('#edit-user-name', 'val' , array($random_user->get('name')->getString())));
// ChangedCommand did not work.
//$ajax_response->addCommand(new ChangedCommand('#edit-user-name', '#edit-user-name'));
// We can still invoke the change command on #edit-user-name so it triggers Ajax on that element to validate username.
$ajax_response->addCommand(new InvokeCommand('#edit-user-name', 'change'));
// Return the AjaxResponse Object.
return $ajax_response;
}
}
@mohsincynexis
Copy link

mohsincynexis commented Apr 4, 2017

Akshay,

Can you please guide me to write ajax for complete form which have multiple fields here is my custom form code`
namespace Drupal\get_price\Form;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ChangedCommand;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Ajax\UpdateBuildIdCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class GetPriceForm extends FormBase
{

public function getFormId()
{
    return 'get_price_form';
}


public function buildForm(array $form, FormStateInterface $form_state) {
    $form['user_full_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Full Name'),
        '#required' => TRUE,
        '#suffix' => '<span class="ui-state-error-text user-full-name"></span>'
    );
    $form['user_email'] = array(
        '#type' => 'email',
        '#title' => t('Email'),
        '#required' => TRUE,
        '#suffix' => '<span class="ui-state-error-text user-email"></span>'
    );
    $form['user_number'] = array (
        '#type' => 'tel',
        '#title' => t('Phone Number'),
        '#attributes'   =>array('class' => array('form-control')),
        '#suffix' => '<span class="ui-state-error-text user-number"></span>'
    );
    $form['user_state'] = array (
        '#type' => 'select',
        '#title' => ('State'),
        '#required' => TRUE,
        '#options' => array(
            'Canada' => t('Canada'),
            'Foreign' => t('Foreign'),
            'Alabama' => t('Alabama'),
            'Alaska' => t('Alaska'),
            'Arizona' => t('Arizona'),
            'Arkansas' => t('Arkansas'),
            'California' => t('California'),
            'Colorado' => t('Colorado'),
            'Connecticut' => t('Connecticut'),
            'Delaware' => t('Delaware'),
            'Florida' => t('Florida'),
            'Georgia' => t('Georgia'),
            'Guam' => t('Guam'),
            'Hawaii' => t('Hawaii'),
            'Idaho' => t('Idaho'),
            'Illinois' => t('Illinois'),
            'Indiana' => t('Indiana'),
            'Iowa' => t('Iowa'),
            'Kansas' => t('Kansas'),
            'Kentucky' => t('Kentucky'),
            'Louisiana' => t('Louisiana'),
            'Maine' => t('Maine'),
            'Marshall Islands' => t('Marshall Islands'),
            'Maryland' => t('Maryland'),
            'Massachusetts' => t('Massachusetts'),
            'Michigan' => t('Michigan'),
            'Minnesota' => t('Minnesota'),
            'Mississippi' => t('Mississippi'),
            'Missouri' => t('Missouri'),
            'Montana' => t('Montana'),
            'Nebraska' => t('Nebraska'),
            'Nevada' => t('Nevada'),
            'New Hampshire' => t('New Hampshire'),
            'New Jersey' => t('New Jersey'),
            'New Mexico' => t('New Mexico'),
            'New York' => t('New York'),
            'North Carolina' => t('North Carolina'),
            'North Dakota' => t('North Dakota'),
            'Northern Mariana Islands' => t('Northern Mariana Islands'),
            'Ohio' => t('Ohio'),
            'Oklahoma' => t('Oklahoma'),
            'Oregon' => t('Oregon'),
            'Palau' => t('Palau'),
            'Pennsylvania' => t('Pennsylvania'),
            'Puerto Rico' => t('Puerto Rico'),
            'Rhode Island' => t('Rhode Island'),
            'South Carolina' => t('South Carolina'),
            'South Dakota' => t('South Dakota'),
            'Tennessee' => t('Tennessee'),
            'Texas' => t('Texas'),
            'Utah' => t('Utah'),
            'Vermont' => t('Vermont'),
            'Virgin Islands' => t('Virgin Islands'),
            'Virginia' => t('Virginia'),
            'Washington' => t('Washington'),
            'West Virginia' => t('West Virginia'),
            'Wisconsin' => t('Wisconsin'),
            'Wyoming' => t('Wyoming')
        ),
        '#attributes'   =>array('class' => array('form-control')),
        '#suffix' => '<span class="ui-state-error-text user-state"></span>'
    );

    $form['product_sku'] = array(
        '#type' => 'textfield',
        '#title' => t('Product SKU'),
        '#required' => TRUE,
        '#suffix' => '<span class="ui-state-error-text product-sku"></span>'
    );

    $form['product_url'] = array(
        '#type' => 'url',
        '#title' => t('Product URL'),
        '#required' => TRUE,
        '#attributes'   =>array('class' => array('form-control')),
        '#suffix' => '<span class="ui-state-error-text product-url"></span>'
    );

    $form['user_message'] = array(
        '#type' => 'textarea',
        '#title' => t('Message to the factory on what part you are looking for information on'),
        '#required' => TRUE,
        '#suffix' => '<span class="ui-state-error-text user-message"></span>'
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#button_type' => 'primary',
        '#attributes'   =>array('class' => array('btn btn-info use-ajax-submit')),//use-ajax-submit
        '#ajax' => array(
            'callback' => '::respondToAjax',
            'event' => 'click',
            'progress' => array(
                'type' => 'throbber',
                'message' => 'Sending...',
            ),

        ),
    );
    //$form['#theme'] = 'get_price_form';
    return $form;
}

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

/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
    /*// Display result.
    foreach ($form_state->getValues() as $key => $value) {
        drupal_set_message($key . ': ' . $value);
    }*/
}


/**
 * @param array $form
 *   Form API array structure.
 * @param array $form_state
 *   Form state information.
 *
 * @return AjaxResponse
 *   Response object.
 */
public function respondToAjax(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $full_name = $form_state->getValue('user_full_name');
    $email = $form_state->getValue('user_email');

    if (empty($full_name))
    {

        $css = ['border' => '1px solid red'];
        $message = t('Please enter your full name');
        $response->addCommand(new CssCommand('#edit-user-full-name', $css));
        $response->addCommand(new HtmlCommand('.user-full-name', $message));

    }
    if ( !\Drupal::service('email.validator')->isValid($email))
    {

        $css = ['border' => '1px solid red'];
        $message = t('Please enter your email');
        $response->addCommand(new CssCommand('#edit-user-email', $css));
        $response->addCommand(new HtmlCommand('.user-email', $message));

    }

    /*$submit_selector = 'form:has(input[name=form_build_id][value='
        . $form['#build_id'] . '])';*/

    //$response->addCommand(new AlertCommand($message));
    $response->addCommand(new UpdateBuildIdCommand($form['#build_id_old'], $form['#build_id']));
    //$response->addCommand(new InvokeCommand($submit_selector, 'submit'));

    return $response;
}` the problem is does not clear the previous error messages. Please guide.

@guaneagler
Copy link

guaneagler commented Jul 5, 2017

Hi, Akshay. Thanks for your share.
I have some questions when I am using hook_form_alter to alter a node add form adding ajax to it. But unfortunately, the ajax submit always to node/add.., below is my code:
This is the alter function.
`use Drupal\Core\Form\FormStateInterface;

function cityu_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['field_type']['widget']['#ajax'] = array(
'callback' => 'Drupal\cityu\Controller\CityUController:ajaxChangeType',
'event' => 'change',
'url' => '/cityu/ajax/type'
);
}`

This is the controller for handle the ajax request:
`namespace Drupal\cityu\Controller;

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

class CityUController {

public function ajaxChangeType($form, FormStateInterface $form_state) {
$ajax_response = new AjaxResponse();
$ajax_response->addCommand(new InvokeCommand('#edit-title-0-value', 'val' , array('hi eagle')));
}
}`

This is the callback defined.

`
cityu.ajax.type:

path: 'cityu/ajax/type'

defaults:

_controller: 'Drupal\cityu\Controller\CityUController::ajaxChangeType'

`

@tonytaylor
Copy link

Hi Akshay. Do you have an example for ['progress']['bar']?
I don't quite understand how to update the progress bar using the AjaxCommands. Do I need to know the selector?

Any help would be greatly appreciated.

Thanks in advance.

@ankit1114
Copy link

i am new in drupal 8

how to submit form through ajax and data store in database and display submit message only in place of form.

select('hello_form', 'm') ->condition('id', $_GET['num']) ->fields('m'); $record = $query->execute()->fetchAssoc(); } $form['#attributes']['enctype'] = 'multipart/form-data'; $form['image'] = array( '#type' => 'managed_file', '#title' => t('Upload your file'), //'#required' => true, '#upload_location' => 'public://images/', '#default_value' => (isset($record['image']) && $_GET['num']) ? $record['image']:'', ); $form['name'] = array( '#type' => 'textfield', '#title' => t('Candidate Name:'), //'#required' => TRUE, '#default_value' => (isset($record['name']) && $_GET['num']) ? $record['name']:'', ); $form['email'] = array( '#type' => 'email', '#title' => t('Candidate Email:'), //'#required' => TRUE, '#default_value' => (isset($record['email']) && $_GET['num']) ? $record['email']:'', ); $form['password'] = array( '#type' => 'password', '#title' => t('Password:'), //'#required' => TRUE, '#default_value' => (isset($record['password']) && $_GET['num']) ? $record['password']:'', ); $form['dob'] = array ( '#type' => 'textfield', '#title' => t('AGE:'), '#default_value' => (isset($record['dob']) && $_GET['num']) ? $record['dob']:'', ); $form['address'] = array( '#type' => 'textfield', '#title' => t('Address:'), '#default_value' => (isset($record['address']) && $_GET['num']) ? $record['address']:'', ); $form['number'] = array( '#type' => 'tel', '#title' => t('Contact number:'), '#required' => TRUE, '#default_value' => (isset($record['number']) && $_GET['num']) ? $record['number']:'', ); $form['gender'] = array( '#type' => 'select', '#title' => $this ->t('Select Gender'), '#options' => [ '' => $this ->t('Select'), 'male' => $this ->t('Male'), 'female' => $this ->t('Female'), 'person' => $this ->t('Person'), ], '#default_value' => (isset($record['gender']) && $_GET['num']) ? $record['gender']:'', ); $form['copy'] = array( '#type' => 'checkbox', '#title' => $this ->t('Send me a copy'), ); /*$form['submit'] = [ '#type' => 'submit', '#value' => 'save', //'#value' => t('Submit'), //'#ajax' => [ //'callback' => '::setMessage', ];*/ $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('save'), '#ajax' => [ 'callback' => '::setMessage', ], ]; $form['message'] = [ '#type' => 'markup', '#markup' => '
', ]; return $form; } public function setMessage(array $form, FormStateInterface $form_state) { $response = new AjaxResponse(); $response->addCommand( new HtmlCommand( '.result_message', '
Submitted Successfully ' . $form_state->getValue('name') . '
') ); return $response; } public function validateForm(array &$form, FormStateInterface $form_state) { /*$field = $form_state->getValues(); $name = isset($field['name']) ? $field['name'] : ''; $email = isset($field['email']) ? $field['email'] : ''; $number = isset($field['number']) ? $field['number'] : ''; if (strlen($name) < 5) { $form_state->setErrorByName('name', $this->t('Name is too short.')); }*/ /*if(preg_match("/^\d+\.?\d*$/",$number) && strlen($number)==10){ } else { $form_state->setErrorByName('number', $this->t('Mobile number is too short.')); } */ } public function submitForm(array &$form, FormStateInterface $form_state) { \Drupal::messenger()->addMessage($this->t('Form Submitted Successfully'), 'status', TRUE); $message = [ '#theme' => 'status_messages', '#message_list' => drupal_get_messages(), ]; $messages = \Drupal::service('renderer')->render($message); echo $messages; $response = new AjaxResponse(); $response->addCommand(new HtmlCommand('#result-message', $messages)); return $response; $field = $form_state->getValues(); $image = !empty($field['image']) ? $field['image'] : ''; $name = isset($field['name']) ? $field['name'] : ''; $email = isset($field['email']) ? $field['email'] : ''; $password = isset($field['password']) ? $field['password'] : ''; $dob = isset($field['dob']) ? $field['dob'] : ''; $address = isset($field['address']) ? $field['address'] : ''; $number = isset($field['number']) ? $field['number'] : ''; $gender = isset($field['gender']) ? $field['gender'] : ''; $field = array( 'image' => $image, 'name' => $name, 'email' => $email, 'password' => $password, 'dob' => $dob, 'address' => $address, 'number' => $number, 'gender' => $gender, ); // DB connection. $conn = Database::getConnection(); if (isset($_GET['num'])){ $conn->update('hello_form') ->fields($field) ->condition('id', $_GET['num']) ->execute(); drupal_set_message("succesfully updated"); $form_state->setRedirect('hello_world.display_table_controller_display'); } else { $conn->insert('hello_form') ->fields($field) ->execute(); drupal_set_message("succesfully saved"); $response = new RedirectResponse(\Drupal::url('hello_world.display_table_controller_display')); $response->send(); } } }

@berliner
Copy link

Impressive how the formatting quality of the code samples deteriorated ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment