Score:4

How to add an item constraint to a field

ke flag

How do I define an item level constraint, as opposed to a constraint on an item list?

In the comments of \Drupal\Core\Field\FieldConfigInterface, there is this note:

   * If you wish to apply a constraint to a \Drupal\Core\Field\FieldItem instead
   * of a property or FieldItemList, you can use the
   * \Drupal\Core\Field\FieldConfigBase::getItemDefinition() method.
   * @code
   *   // Add a constraint to the 'field_entity_reference' FieldItem (entity
   *   // reference item).
   *   $fields['field_entity_reference']->getItemDefinition()->addConstraint('MyCustomFieldItemValidationPlugin', []);

Presumably this would be run inside hook_entity_bundle_field_info_alter()?

I am trying this as shown here. It accepts the constraint, you can see it in the definition, but it never runs.

Is there some further undocumented detail for doing this? Or is this the wrong hook?

Score:1
cn flag

This hook seems indeed not to be the right place. When the item definitions are recreated later your custom code will not run again.

More common are constraints on the field property, which are added in a persistent way to the field item via the property constraint table of the field definition. To fill this table use addPropertyConstraints():

function mymodule_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  $field_name = 'field_example';
  if ($entity_type->id() == 'entity_test' && $bundle == 'entity_test' && !empty($fields[$field_name])) {
    // Add a property constraint using
    // \Drupal\Core\Field\FieldConfigInterface::addPropertyConstraints().
    $fields[$field_name]->addPropertyConstraints('value', [
      'Range' => [
        'min' => 0,
        'max' => 32,
      ],
    ]);
  }
}

Code is from field_test.module.

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.