I had a Drupal project where I need to submit a form without reloading the page so I used Form API #ajax parameter to execute my custom callback function and validate the form.
Sample FORM:
function MODULENAME_bid_form($form, &$form_state) {
$prices = array(
0 => t('Select a bid amount'),
10000 => '+ P 10,000',
20000 => '+ P 20,000',
30000 => '+ P 30,000',
);
$form['wrapper'] = array(
'#type' => 'container',
'#prefix' => '<div id="bid-wrapper">',
'#suffix' => '</div>',
);
$form['wrapper']['bid_price'] = array(
'#type' => 'select',
'#options' => $prices,
'#required' => TRUE,
'#default_value' => 0,
'#disabled' => TRUE,
);
$form['wrapper']['submit'] = array(
'#type' => 'submit',
'#value' => t('Bid Now!'),
'#disabled' => TRUE,
'#ajax' => array(
'callback' => 'MODULENAME_bid_form_callback',
'wrapper' => 'box',
'event' => 'click',
),
);
return $form;
}
The ajax callback:
function MODULENAME_bid_form_callback(&$form, &$form_state) {
$commands = array();
$commands[] = ajax_command_remove('#messages-wrap');
$commands[] = ajax_command_before('#bid-wrapper', '<div id="messages-wrap">' . theme('status_messages') . '</div>');
$commands[] = ajax_command_replace('.field-name-field-current-bid .field-item', '<div class="field-item">New item value</div>');
return array('#type' => 'ajax', '#commands' => $commands);
}
We also need to display an alert message before submitting the form asking if they want to continue or cancel.
Below is the code snippet that I used to prevent the execution of Drupal ajax when cancel is clicked.
(function ($) {
'use strict';
Drupal.behaviors.ReplaceWithAnyTextYouWant = {
attach: function (context, settings) {
// 'edit-submit' is the element ID where you execute the #ajax.
Drupal.ajax['edit-submit'].options.beforeSubmit = function(form_values, element_settings, options) {
// If cancel is clicked, do not continue submitting.
if (!confirm('Are you sure you want to continue?') {
return false;
}
}
};
})(jQuery);
You can also use this method to run a client side validation before submitting the form.
There are parameters available on the beforeSubmit that we can use like the form_values.
form_values will return an object where it contains the submitted form name and values. We can extract the value by using the code below:
Drupal.ajax['edit-submit'].options.beforeSubmit = function(form_values, element_settings, options) {
var bid_price = 0;
for (var key in form_values) {
console.log(form_values[key]); // This will display the object values on the console log.
if (form_values[key]['name'] == 'bid_price') {
bid_price = form_values[key]['value'];
}
}
}
by Mark Jayson Gruta on July 08, 2015