You are here

public function FieldConfigInterface::addConstraint in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Field/FieldConfigInterface.php \Drupal\Core\Field\FieldConfigInterface::addConstraint()
  2. 10 core/lib/Drupal/Core/Field/FieldConfigInterface.php \Drupal\Core\Field\FieldConfigInterface::addConstraint()

Adds a validation constraint to the FieldItemList.

Note: If you wish to apply a constraint to just a property of a FieldItem use \Drupal\Core\Field\FieldConfigInterface::addPropertyConstraints() instead.

// Add a constraint to the 'field_username' FieldItemList.
// e.g. $node->field_username
$fields['field_username']
  ->addConstraint('UniqueField');

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.

// Add a constraint to the 'field_entity_reference' FieldItem (entity
// reference item).
$fields['field_entity_reference']
  ->getItemDefinition()
  ->addConstraint('MyCustomFieldItemValidationPlugin', []);

See \Drupal\Core\TypedData\DataDefinitionInterface::getConstraints() for details.

Note that constraints added via this method are not stored in configuration and as such need to be added at runtime using hook_entity_bundle_field_info_alter().

Parameters

string $constraint_name: The name of the constraint to add, i.e. its plugin id.

array|null $options: The constraint options as required by the constraint plugin, or NULL.

Return value

static The object itself for chaining.

Overrides DataDefinitionInterface::addConstraint

See also

\Drupal\Core\Field\FieldItemList

\Drupal\Core\Field\FieldConfigInterface::addPropertyConstraints()

hook_entity_bundle_field_info_alter()

1 method overrides FieldConfigInterface::addConstraint()
FieldConfigBase::addConstraint in core/lib/Drupal/Core/Field/FieldConfigBase.php
Adds a validation constraint to the FieldItemList.

File

core/lib/Drupal/Core/Field/FieldConfigInterface.php, line 255

Class

FieldConfigInterface
Defines an interface for configurable field definitions.

Namespace

Drupal\Core\Field

Code

public function addConstraint($constraint_name, $options = NULL);