0

I'm using a number of Ajax form, and while the I can get the error validation to work, and present the error message using the following:

  if (null !== form_get_errors()):
    return array(
      '#type' => 'ajax',
      '#commands' => array(
        ajax_command_remove('.alert-dismissable'),
        ajax_command_prepend('#myErrorDiv', theme('status_messages')),
      ),
    );
  endif;

However, I am unsure how to highlight the specific fields (usually done by adding a 'error' class to the form item.)

What the best way to achieve this, or is there a better way to handle the form errors that does not take over the normal error highlighting and message display?

1 Answer 1

1

Not as hard as I thought, but for anyone else trying to solve the same issue, you need to get all the relevant fields from form_get_errors() and add the error class to the same - note I also clear the previous errors:

if (null !== form_get_errors()):
  $commands[] = ajax_command_invoke('#myFormDiv .form-item.error', 'removeClass', array('error'));
  $commands[] = ajax_command_remove('.alert-dismissable');
  $commands[] = ajax_command_prepend('#myErrorDiv', theme('status_messages'));
  foreach (form_get_errors() as $field => $message) :
    $commands[] = ajax_command_invoke('.form-item-'.$field, 'addClass', array('error'));
  endforeach;
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );   
endif;

Note that your $field will be dependent in what you've set in your validation function, so you might need to do some funky things to make sure '.form-item-'.$field is finding the right div.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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