How to Make Fields Persistent in Drupal 8

preview_player
Показать описание
By: Ivan Zugec

I wrote a custom module recently where I needed to programmatically attach a field; similar to how a Body field is added to content types.

If you create a content type, via the "Content types" page, a Body field is automatically added to the content type. If you don't need the field just delete it, but the default functionality is to have it added.

I needed this same functionality in my custom module; when an entity is created a field is programmatically attached to it.

I implemented my custom module in a similar fashion and everything worked until all the entity bundles with the custom field were deleted. When a new entity type was created you'd get a fatal error saying the custom field, which was programmatically attached, doesn't exist.

So what happened?

Drupal by default will delete a field if it's no longer used. Now the fix for this is pretty simple.

Simply set persist_with_no_fields to TRUE in the yaml file. For example, persist_with_no_fields: true.
Рекомендации по теме
Комментарии
Автор

Thanks for the hint Ivan. Core source code is a huge repository of knowledge.

marek