D8 Logo
CMS

Drupal 8: Modify Field Definition without Data loss

Drupal ships with different types of field types, which can be used to organize our data. Some are –  Booleandatetime, daterangedecimalentity_reference, filefloatimageinteger, link, list_floatlist_integerlist_stringstring, string_longtexttext_long, text_with_summary.

But usually what happens is with the cause of development we may came to a situation where we need to change the field definition of a particular field.  But this is not be possible to do with the UI as the from UI we need to delete the old field first and then create new one in the required field definition, which will delete the already added data to the fields. So here I explain a way to change the field definition without data loss.

For example, lets say we need to store text for one content type so we will go for the string_long option, but in later point of time what if we need to make it text_long or  text_with_summary, so that we can add HTML content as well to the same.  One option is to delete the field and  create a new field with the desired field type. But this will not be always a possible solution,  as this will lead to data loss.

So, here is a solution the field definition.  The below example show how we can change the field type string(plain text) to text(formatted).

Create a custom module if you don’t have one and then we need to add the below code to the *.install file (* is your module name).

In *.install file add the classes we want to use.

Next we need to define the update hook

Now we need the below steps to achieve the result.

Step 1: Get field storage Get field storage.

Step 2: Store data in the field to an array so that we can restore it once the update is complete.

Step 3: Save new field configs & delete existing fields.

Step 4: Create new storage configs from existing.

Step 5: Purge deleted fields data to create new fields.

Step 6: Create new field storage.

Step 7: Create new fields for all bundles.

Step 8: Restore existing data in fields & revision tables.

So here is the complete solution.

Step 10: Run the database update.

 

Result

Once all these steps are done we can see the updated field definition in the Field UI.

Note: After the update if the field is not displayed in entity view, please add it back from manage display.

About The Author

Leave a Reply

*