field_attach_validate() is meant to be called to validate field values when saving entities programmatically:

  $values = array(
    'type' => 'article',
  );
  $node = entity_create('node', $values);
  // There is no term with this tid.
  $node->field_tags[LANGUAGE_NONE][0]['tid'] = 1000000;

  field_attach_validate('node', $node);

The above throws an exception:

FieldValidationException: Field validation errors in field_attach_validate() (line 801 of modules/field/field.attach.inc).

This is expected and correct.

However, it also causes error messages:

Notice: Undefined offset: 1000 in taxonomy_field_validate() (line 1519 of /Users/joachim/Sites/yes-canvassing/modules/taxonomy/taxonomy.module).
Notice: Trying to get property of non-object in taxonomy_field_validate() (line 1519 of /Users/joachim/Sites/yes-canvassing/modules/taxonomy/taxonomy.module).
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

joachim’s picture

Title: Undefined offset: 1000 in taxonomy_field_validate() when validating an term ref field with a non-existent term » Undefined offset in taxonomy_field_validate() when validating an term ref field with a non-existent term
Status: Active » Needs review
FileSize
848 bytes
donquixote’s picture

I agree with the problem description. However:
- It checks !isset($terms[$item['tid']]) even if $item['tid'] is empty, or 'autocreate'.

Here is a patch that fixes this, and that also simplifies the code:

  • Iterate over $tids instead of $items.
  • Use !== instead of != where applicable. This also allows different start value for $validate.
  • Check $tids !== array() instead of !empty($tids). Doing this allows the IDE to warn us if $tids is an undefined variable (which it is not, but it is a good idea in general).

Some things that I would wish to change, but am not addressing in this patch:

  • Rename $validate to $tid_is_allowed.
  • Or alternatively, eliminate the $validate variable, and use continue statements instead.
  • Show a distinct warning, if the term does not exist.

I am not providing an interdiff, because the patches are just too different.

donquixote’s picture