I have created custom field_type for a field in my content type. The field 'field_content_category' already exists and is an entity_reference. Changing the yml file and importing doesnt work because there is already data for the field.

My custom field_type is an entity reference and a field to type in an integer.

How do I change the field field_type without creating a new field?

  • Not sure if this is what the question is about. Can't you change the widget in the ui at /admin/structure/types/manage/[content-type]/form-display? – 4k4 Jul 13 '16 at 18:44
  • not quite. Unless i dont know what Widget means. At that path i can change some configuration on the widget. The field is currently an entity_autocomplete on taxonomy terms. i can change the size and whether it searches by starts with or contains. it doesnt change the widget itself. – BrandenB171 Jul 13 '16 at 18:52
  • You are not using the word 'widget' correctly. What you are trying to change is the 'field type'. Check the Field Types API of Drupal. – Maouna Jul 13 '16 at 19:12

To change the field type you would have to write an update_hook:


function entity_test_update_8001() {
  // To update the field schema we need to have no field data in the storage,
  // thus we retrieve it, delete it from storage, and write it back to the
  // storage after updating the schema.
  $database = \Drupal::database();

  // Retrieve existing field data.
  $user_ids = $database->select('entity_test', 'et')
    ->fields('et', ['id', 'user_id'])

  // Remove data from the storage.
    ->fields(['user_id' => NULL])

  // Update definitions and schema.
  $manager = \Drupal::entityDefinitionUpdateManager();
  $storage_definition = $manager->getFieldStorageDefinition('user_id', 'entity_test');

  // Restore entity data in the new schema.
  $insert_query = $database->insert('entity_test__user_id')
    ->fields(['bundle', 'deleted', 'entity_id', 'revision_id', 'langcode', 'delta', 'user_id_target_id']);
  foreach ($user_ids as $id => $user_id) {
    $insert_query->values(['entity_test', 0, $id, $id, 'en', 0, $user_id]);
  • so in this example, is entity_test my Content Type and user_id the field i wanna change? – BrandenB171 Jul 13 '16 at 20:51
  • Also this is just changing Cardinality api.drupal.org/api/drupal/… nothing in here seems to change the field type – BrandenB171 Jul 14 '16 at 19:50
  • This is example is for the general problem, how to change the field definition if there is data stored in the field. – 4k4 Jul 14 '16 at 20:33
  • Do you know of a way to change the field type? – BrandenB171 Jul 14 '16 at 20:39

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.