I created a form in Drupal 7 and want to use AJAX. I added this to the submit button array:
"#ajax" => array(
"callback" => "my_callback",
"wrapper" => "details-container",
"effect" => "fade"
)
This works but the whole validation function is ignored. How can I validate the form before my_callback()
is called? And how can I display the status or error messages on a AJAX form?
Enable the submit button in the input form. If the <valid/> element value is false, set the HTML of the validationMessage div element in Catalog ID field row to "Catalog Id is not Valid". Disable the submit button, and set the values of the other input fields. Next, run the Ajax application in JDeveloper 10.1.
AJAX form submitting allows you to send data in the background, eliminating the need to reload websites to see the updates. This makes the user experience much smoother.
This question and answer helped guide me to the right solution, but it isn't exactly crystal clear. Let's make it so.
Things to be very aware of:
#ajax['wrapper']
#markup
, but rather because he is including the div with the wrapper id set.Here is code that was working for me based off what Marius put in the comment above:
function dr_search_test_form($form, &$fstate) {
$form["wrapper"] = array("#markup" => "<div id='test-ajax'></div>");
$form["name"] = array(
"#type" => "textfield",
"#required" => true,
"#title" => "Name"
);
$form["submit"] = array(
"#type" => "submit",
"#value" => t("Send"),
"#ajax" => array(
"callback" => "dr_search_test_form_callback",
"wrapper" => "test-ajax",
"effect" => "fade",
),
);
return $form;
}
function dr_search_test_form_callback($form, &$fstate) {
return "<div id='test-ajax'>Wrapper Div</div>";
}
function dr_search_test_form_validate($form, &$fstate) {
form_set_error("name", "Some error to display.");
}
I found an excellent solution to this problem.
Credit goes to this guy's blog:
http://saw.tl/validate-form-ajax-submit-callback
The solution he proposes is the following:
// when creating or altering the form..
{
$form['#prefix'] = '<div id="formwrapper">';
$form['#suffix'] = '</div>';
// the submit button
$form['save']['#ajax'] = array(
'callback' => 'mymodule_form_ajax_submit',
'wrapper' => 'formwrapper',
'method' => 'replace',
'effect' => 'fade',
);
// ...
}
function mymodule_from_ajax_submit($form, &$form_state) {
// validate the form
drupal_validate_form('mymodule_form_id', $form, $form_state);
// if there are errors, return the form to display the error messages
if (form_get_errors()) {
$form_state['rebuild'] = TRUE;
return $form;
}
// process the form
mymodule_form_id_submit($form, $form_state);
$output = array(
'#markup' => 'Form submitted.'
);
// return the confirmation message
return $output;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With