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; | |
} | |
} |
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'
`
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.
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', 'Impressive how the formatting quality of the code samples deteriorated ..
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
{