Score:0

How can I setRequired() for a BaseFieldDefinition per entity bundle?

cn flag

I have an entity type animal with the following bundles:

  • cow
  • pig
  • sparrow
  • anteater

In the Animal.php entity type definition, I create some base fields, one of which is an entity reference to Habitat.

BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Habitat ID'))
  ->setCardinality(1)
  ->setSetting('target_type', 'habitat')
  ->setDisplayConfigurable('form', FALSE)
  ->setDisplayConfigurable('view', TRUE);

I want to require this entity reference for cows and pigs, but I don't want it to be required for sparrows and anteaters.

So, I can't use ->setRequired() in BaseFieldDefinition::create() because that will apply to all the bundles.

What's the simplest way to require a field created by BaseFieldDefinition::create() in some bundles but not others?

4uk4 avatar
cn flag
The simplest way is to store an override in config. See https://drupal.stackexchange.com/questions/253257/how-to-easily-alter-an-entitys-base-field-definition-per-bundle
Score:0
de flag

I haven't done it, but I believe you can override ContentEntityBase::bundleFieldDefinitions(), returning the fields based on the bundle type.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.