/sites/default/files/2023-10/website-html-code-browser-view-printed-on-white-paper-closeup-view_0.jpg
Faced an interesting problem when maintaining a Drupal site. It occurs in all versions of Drupal. Problem: It is possible to create an entity with label "0". However, this entity will be ignored by the entity autocomplete form element.
Steps to reproduce
Create a new term with name "0". Take any node type and configure a new field that refers to terms. Set any autocomplete widget for this field. Take any node of this type and open the edit form. Input "0" in the field - there are no autocomplete suggestions. After saving the node, the field will remain empty. However, if you input "0 " (trailing space), then the field value will be saved correctly.
Solution
See here for a description of the problem and patches.
Fix for terms without a core patch (Drupal 7).
/**
* Implements hook_field_widget_WIDGET_TYPE_form_alter().
*/
function custom_field_widget_taxonomy_autocomplete_form_alter(&$element, &$form_state, $context) {
array_unshift($element['#element_validate'], 'custom_taxonomy_autocomplete_validate');
}
/**
* Form element validate handler for taxonomy term autocomplete element.
*
* @param array $element
* The element structure.
*/
function custom_taxonomy_autocomplete_validate(array &$element) {
// Fix for single term with name "0".
if ($element['#value'] === '0') {
$element['#value'] .= ' ';
}
}
Add new comment