function FieldConfigInterface::addConstraint
Same name in other branches
- 9 core/lib/Drupal/Core/Field/FieldConfigInterface.php \Drupal\Core\Field\FieldConfigInterface::addConstraint()
- 8.9.x core/lib/Drupal/Core/Field/FieldConfigInterface.php \Drupal\Core\Field\FieldConfigInterface::addConstraint()
- 11.x 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
File
-
core/
lib/ Drupal/ Core/ Field/ FieldConfigInterface.php, line 255
Class
- FieldConfigInterface
- Defines an interface for configurable field definitions.
Namespace
Drupal\Core\FieldCode
public function addConstraint($constraint_name, $options = NULL);
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.