Form validation woes/answers.

Events happening in the community are now at Drupal community events on www.drupal.org.
craigmc's picture

Hi all--
Muscled through this bear of an issue and wanted to share my story.

Building an ubercart site, and need to customize the /cart/checkout page to allow a user to log in from there.

Used hook_form_alter to add the necessary fields and a custom submit button. Added my own validation function, and inserted it before the ubercart validation function:

array_unshift($form['#validate'], 'MYMODULE_uc_cart_checkout_form_validate');

Issue I was running into is that there are a bunch of #required fields in this form. It is a little taxing programatically to remove the #required tag from all of Ubercart's fields because they're buried very deep in the form's structure, so I found a better approach that works great.

Note:
My validate function only happens if someone clicks my login link-- you wouldn't want to follow my approach for a general case validation function.

  if ($form_state['values']['login'] == 'Log In') {
        drupal_get_messages('error');  //clears out messages thrown by built in validation-- since we are ignoring Required fields for this
      form_set_error(NULL,'', TRUE);
                 ...

The reason this was necessary is that I was using user_authenticate() to actually attempt the login, which checks for form_set_errors() before approving the login, so I had to clear out any errors from the #required form elements otherwise user_authenticate would never work.

Anyhoo, that's my bit of knowledge for the night. Let me know if you have any questions.

If nested forms were a possibility, that would be a better way to go, but we gotta work with what we got.... :)

Comments

Thx for sharing!

Techivist's picture

Thx for sharing this, Craig! Always good to hear any tips/tricks that make life easier & it seems like you accomplished this. Hopefully, you didn't pull all your hair out in the process :)

Miguel Hernandez - www.migshouse.com
Founder & CEO - The OpenMindz Group
Writer- Linux Journal & TechZulu