/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 object labelled "0". However, this object will be ignored by the autocomplete object form element.

See here for a description of the problem and patches

Solution

Create a new term named "0". Select any type of node and configure a new field that references the terms. Install any autofill widget for this field. Select any node of this type and open the edit form. Enter "0" in the field — there will be no suggestions for autofill. After saving the node, the field will remain empty. However, if you enter "0" (separated by a space), the value of the field will be saved correctly.

Do not use empty() to check the value of a form element. Don't use (bool) cast to check the entered string from the URL.

Correction for terms without a kernel 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