1

I have a developing a website with a reference term field with multi value. But after the client change the "rules" I need to change the field from multi value to a single value field, but the field as Data, lot's of data.

Is it possible to change from multi value to single value? (the field only as one value inserted and the real object is to use those values).

2 Answers 2

1

Use VBO

Introduce a new, single-value field in the bundle, then use Views Bulk Operations (VBO) to copy the data from the old multi-value field to the new single-value.

VBO have an option to "Execute Arbitrary PHP Script" where you can insert a PHP-snippet to do the copying, something like:

$object->field_foo['und'][0]['value'] = $object->field_bar['und'][0][1]['value'];

The PHP above is only an example. Use dsm($object); (requires Devel installed) to figure out the datastructure of the entity object you need to manipulate.

When done, delete the multi-value field.

Alternate solution: Node convert

It is also possible to do bulk conversion with Node convert.

To use this method, you first clone the content type, then change the multi-value field into a single-value field in the clone. Node Convert let you map content field by field, so you copy most fields directly, and then copy the first value of the multi-value field into its corresponding field.

The disadvantage with this method is that the machine name of the type changes, so you may need to fix that in a number of places if it is used a lot. The advantage that you can do it all in the GUI, no need to write PHP.

0

To do this without changing the database, you could use a custom module to leave the database field as-is multivalue, but change the UI so it only allows users to see/choose a single value by altering the edit form to use a single-value dropdown:

/**
 * 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-article-form', 'node-org-article-form'])) {
    $form['field_multi_thing']['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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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