One field with both Single and Multiple value by content type

Interesting Request of the Week: 

We have a Departments taxonomy that we use on all our content types to relate the content to a particular department or departments.   It supports unlimited choices.

We also have a Departments content type that also should contain the same departments taxonomy (so we can link the node and the term).

The Challenge: We want the Departments taxonomy term-reference field on the Departments content-type to only allow selecting a single value, since the node and the term are a 1:1 relationship.

Our initial recommendation was to normalize the data on the site and either:

  • change the Department term reference fields into Department content-type references, then remove the Department vocabulary
  • add the needed fields on the Department content type to the Department vocabulary and use it there

Unfortunately, in the time available in the current sprint they couldn't change the schema.

The Drupal-related issues involved in this request are:

  • You can't change the cardinality (number of values) in a field once it has data in it (at least not easily).
  • They needed to use the same Department term reference field, since it was used in a site-wide search facet and they wanted the Department node to be returned in the search results with all the related data. 

We showed them how to change how to "fake" a single-value field by adding this following function in a custom module:

/*
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Change multivalue field in database to single-value field on node create/edit pages.
  if (in_array($form_id, ['node-department-form', 'node-department-edit-form'])) {
    $form['field_department']['widget']['#multiple'] = false;
  }
}

This is particularly useful if you have a base field that is shared across content types that needs to be multi-value on some content types, but single-value on others.  

Note: If you edit and save a field that HAD multiple values, it will only have the single selected value after saving, so beware of data loss possibiliities.