function FieldTestHooks::entityBundleFieldInfoAlter

Implements hook_entity_bundle_field_info_alter().

Attributes

#[Hook('entity_bundle_field_info_alter')]

File

core/modules/field/tests/modules/field_test/src/Hook/FieldTestHooks.php, line 105

Class

FieldTestHooks
Hook implementations for field_test.

Namespace

Drupal\field_test\Hook

Code

public function entityBundleFieldInfoAlter(&$fields, EntityTypeInterface $entity_type, $bundle) : void {
  if (($field_name = \Drupal::state()->get('field_test_constraint', FALSE)) && $entity_type->id() == 'entity_test' && $bundle == 'entity_test' && !empty($fields[$field_name])) {
    // Set a property constraint using
    // \Drupal\Core\Field\FieldConfigInterface::setPropertyConstraints().
    $fields[$field_name]->setPropertyConstraints('value', [
      'TestField' => [
        'value' => -2,
        'message' => "{$field_name} does not accept the value -2.",
      ],
    ]);
    // Add a property constraint using
    // \Drupal\Core\Field\FieldConfigInterface::addPropertyConstraints().
    $fields[$field_name]->addPropertyConstraints('value', [
      'Range' => [
        'min' => 0,
        'max' => 32,
      ],
    ]);
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.