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;
}
}
@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