Ways to shoot yourself in the foot: element validation

Submitted by Marc on Thu, 07/24/2014 - 10:21pm

I needed to do some custom validation of fields on a form. So, I decided to use #element_validate. One of the fields I was validating appeared a bit strange to me, though. When I displayed its $form_state['values']['field_face_palm'] information I saw that it looked like:

$field_face_palm['und'] = 'you_knucklehead'

instead of like:

$field_face_palm['und'][0]['value'] = 'you_knucklehead'

Well, I figured that's just the way it was. I couldn't imagine why Drupal would be formatting the information differently, but I couldn't change it. So, I wrote and tested my code on my local development environment and pushed it up to the public test environment.

The validation did not work properly on the public test environment. To start debugging, I once again displayed the field information. This time it did correspond to the usual pattern.

I was completely stumped as to what was different between the two environments and figured that the error must be on my local environment. So, I was going to need to do more experimentation in my local environment.

In the process of testing different things, I used a $form['#validate'] and noticed that in that validation function the field was also formatted as I would have expected. So, the field was getting formatted properly at some point.

I guess I need to come clean at this point. Even though I was using element validation, I was comparing one element to others in some of the validation functions, as opposed to looking only at the element that was being validated. My issue was that the element in question had not yet been fully formatted when I was inside a different element validator function.

I still don't have an answer of why the element was fully formatted in the public test environment but not in my local development environment. I was using Features, which should guarantee that the content types were defined in exactly the same way. Nonetheless, it makes sense that one shouldn't make any assumptions about the state of any other fields when inside the validation function for a particular field. The proper approach for the situation in which one field needs to be compared to another is to use a form validation function.