1

I need to alter the element value of a taxonomy autocomplete field before it is processed and can't seem to find a way of doing so.

taxonomy autocomplete fields have an element validator attached, that replaces the String value with an array of terms:

[$form] (array)
  [field_myautocomplete] (array)
    [und] (array)
      [#element_validate] (array)
        [0] => "taxonomy_autocomplete_validate" (string)

I need to alter the String before the validator taxonomy_autocomplete_validate() // taxonomy.module:1747 passes it to drupal_explode_tags() // common.inc:7416. Thus I attach my own element validator via hook_form_alter():

[$form] (array)
  [field_myautocomplete] (array)
    [und] (array)
      [#element_validate] (array)
        [0] => "MYMODULE_validate" (string)
        [1] => "taxonomy_autocomplete_validate" (string)

My validator is executed first and uses form_set_value() to update the value (exactly what taxonomy.module:1782 does in its validator).

However, this only updates the value for $form_state and not $element which is the value used by taxonomy_autocomplete_validate(). Thus, the altered value is completely ignored and gets overwritten by the second validator, based on the original string.

Any suggestions beyond hacking core (make taxonomy_autocomplete_validate use $form_state) are most welcome.

  • I guess I could remove the core validator entirely and implement a copy myself that honors $form_state - not very DRY though. – cjoy Aug 8 '14 at 16:53
1

the simple solution to this issue, is to pass $element by reference to the first element validator:

function MYMODULE_validate(&$element, &$form_state) {
  (...)
  form_set_value($element, $new_value, $form_state);
  $element['#value'] = 'new_value';
}

This way, the $element['#value'] (used by the taxonomy_autocomplete_validate) can be modified and the following validators will.

The form_set_value() is not required, but since the form value has changed, it makes sense to update the state as well.

* many thanks to @ciss for helping troubleshoot the issue on #drupal and suggesting the pass by reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.