4

I have a form, that when it's submitted, should be validated, and if valid, the results of that form should then appear below the form.

This works fine without AJAX:

function _form_validate($form, &$form_state) {
  if (!is_numeric($form_state['vsalues']['zip'])) {
    form_set_error('zip', 'Zip must be number');
  }
}

function _form_submit($form, &$form_state) {
    $values = $form_state['values'];
    $html = "<p>zip: ". $values['zip'] . "</p>";
    $form_state['storage'] = $html;
    $form_state['rebuild'] = TRUE;
 }

and then this gets printed out my main form in

  $form['output'] = array(
    '#markup' => (isset($form_state['storage']))?$form_state['storage']:'',
  );

If I make it an AJAX form, and change the submit function to:

function _form_submit($form, &$form_state) {
    $values = $form_state['values'];
    $html = "<p>zip: ". $values['zip'] . "</p>";
    $form_state['storage'] = $html;
    $form_state['rebuild'] = FALSE;
    return array("#markup" => $html);
}

It works fine apart from the fact the submit callback is triggered even when validation fails (e.g. passing a non-numeric value shows both a validation error yet also prints "zip: ").

What am I doing wrong? How can I stop the submit function being called?

  • 1
    I'm getting the exact same error, I'll let you know if I find the answer. – Alex Weber Jul 27 '12 at 4:48
1

Only thing you should have to put in your AJAX submit callback is this

  if (!form_get_errors()) {
    // Do your processing
  }
  else {
    // Return your form with errors.
   return $form;
  }
0

I admitedly couldn't find an elegant solution for this but I found a decent workaround that solved my problem.

In my validation callback:

// Track errors and submissions ourselves.
$form_state['form_has_errors'] = FALSE;
$form_state['form_was_submitted'] = FALSE;

if ($condition) {
  form_set_error($form['fieldname'], t('Error message'));
  $form_state['form_has_errors'] = TRUE;
}

In the submit callback:

// Check for our custom error flag.
// For some reason form_get_errors() is empty, even when validation errors ocurred.
if (!$form_state['form_has_errors']) {
  // Put your submit callback code here.

  $form_state['form_was_submitted'] = TRUE;
}

In the AJAX callback:

if ($form_state['form_was_submitted']) {
  // Do something different here.
}
else {
  // For has errors and wasn't submitted.
}

Again, this is admittedly NOT an elegant solution but I couldn't find any other way to make Drupal not call the submit callback if errors were found.

0

Try to put it in hook_node_validate. if your form is built using content type then it will definitely help you.

Another way might help you like, check it in hook_node_presave() and make exit() call if your validation got fails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.