Undefined index: field in field_widget_field()

A few days ago, my colleague was building a custom form in Drupal 7. Everything was going great until he added a file field, at which point all hell broke loose. The data didn't submit and he received these notices:

Notice: Undefined index: field in field_widget_field() (Row 578 of ...)
Notice: Undefined index: instance in field_widget_instance() (Row 603 of ....)

Since the field was using a custom widget, we were first debugging there, until we finally found the real culprit somewhere completely else: passing by reference.

The hook_form in Drupal 7 has two parameters: $form and $form_state. What many developers forget and mostly isn't that big a deal, but proved to be critical in this case is passing the $form_state by reference. If you are seeing the above notices, first make sure you haven't forgotten the ampersand (&) before blaming anything else.

For reference, this is the correct code:

/**
 * Implements hook_form().
 */
function MYMODULE_form($form, &$form_state) {
  
  // Your code here

}

 

Add new comment

Restricted HTML

  • Allowed HTML tags: <em> <strong> <code> <span>
  • Lines and paragraphs break automatically.
Comments