AJAX form validate and submit

Marius Ilie picture Marius Ilie · Oct 26, 2011 · Viewed 36.5k times · Source

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?

Answer

Joshua Stewardson picture Joshua Stewardson · Jun 28, 2012

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:

  1. Validation error messages will be placed inside whatever is specified as the #ajax['wrapper']
  2. Pay close attention to where the Drupal Forms API documentation of the ajax wrapper says that "the entire element with this ID is replaced, not just the contents of the element."
  3. Because that element is replaced, you had better provide it again. That is why Marius Ilie's answer works - not because of the array and #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.");
}