The way the element validate function in the field example gets the values out of $form_state is unnecessarily complex and will break if the field module's form structure changes. In fact, a comment acknowledges this:

  $delta = $element['#delta']; // TODO: Isn't there a better way to find out which element?
  $field = $form_state['field'][$element['#field_name']][$element['#language']]['field'];
  $field_name = $field['field_name'];
  if (isset($form_state['values'][$field_name][$element['#language']][$delta]['rgb'])) {
    $values = $form_state['values'][$field_name][$element['#language']][$delta]['rgb'];

I fixed it to use $element['#parents'], which is the exact mirror image of what form_set_value() does, so it is unlikely to break. Patch to follow...

Comments

NealB-1’s picture

StatusFileSize
new2.1 KB
rfay’s picture

Thanks @NealB! This is great.

I spent a little time learning from the Field Example this week and thought the examples, though good, were way too complex in general. I'd like to see us add a field that implements a single column and a field that just implements two columns. Those are entry level fields for sure. You're invited on those as well :-)

NealB-1’s picture

@rfay: Thanks. I might give it a shot.

mile23’s picture

Title: Field example element validate function can be simplified » 3text field validation fundamentally flawed
Version: » 7.x-1.x-dev
Status: Needs review » Needs work

Using #parent is much more elegant and readable. Thanks, NealB.

However, field_example_3text_validate() looks like an implementation of hook_field_validate(), but it isn't. What ends up happening is that if you enter a string of the wrong length in any of the 3 text fields, you end up with two error messages:

Saturation value must be a 2-digit hexadecimal value between 00 and ff.
Color must be in the HTML format #abcdef.

This is because we're not using Field API to validate the 3text widget. :-) Form API does it's thing on the widget, and then Field API does its thing on the field. So even though it's validated twice, it's not such a good example of how to implement Field API.

Needs a bunch of work, obviously.

garbo’s picture

I was copying the example for my own module and was running into the exact problem. The patch at #1 saved me.

jungle’s picture

Issue summary: View changes
Status: Needs work » Closed (outdated)

No activity for over 10 years. I am closing this. Please feel free to reopen if necessary.

Thanks!