0

So I want to store an entity_type in a string field in my content entity.

Since the list of entities can change over time, I can't use a list_string field with allowed options. I don't know if calling out to entity_manager would even work properly in that context.

So my current plan just to use a string field and somehow validate that the values the system attempts to save are valid entity type machine names.

How can I perform this validation at the field level? At the entity form level, I will obviously have to add a custom select field and interpret/set the value in the (entity form class)::save() method.

1

list_string can have an allowed_values_callback instead of a list of allowed values, that allows you to return a dynamic list from that callback.

See callback_allowed_values_function(), which has pretty good documentation, that we've refined over multiple issues.

Make sure you're aware of the rules and limitations of what you can return.. for example that not passing an entity should always return all allowed values and passing one it can only limit those and not add more. And that returning new allowed values is not a problem, but not returning them anymore can be problematic as you might end up with data in your database that is no longer valid. The UI doesn't allow you to do that, for example.

  • Sometimes entity types might disappear though if I uninstall modules; in your opinion, what's the best way to deal with this? Does Drupal fire a hook before it deletes an entity, such that I could update the values in my entity to something else (or the default) so they will still be valid? – wizonesolutions Apr 20 '15 at 11:17
  • There's an event that you can listen in now, see EntityTestDefinitionSubscriber for a simple example. – Berdir Apr 20 '15 at 12:06

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.