You are here

public function FieldConfigBase::addConstraint in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Field/FieldConfigBase.php \Drupal\Core\Field\FieldConfigBase::addConstraint()
  2. 10 core/lib/Drupal/Core/Field/FieldConfigBase.php \Drupal\Core\Field\FieldConfigBase::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 FieldConfigInterface::addConstraint

See also

\Drupal\Core\Field\FieldItemList

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

hook_entity_bundle_field_info_alter()

File

core/lib/Drupal/Core/Field/FieldConfigBase.php, line 553

Class

FieldConfigBase
Base class for configurable field definitions.

Namespace

Drupal\Core\Field

Code

public function addConstraint($constraint_name, $options = NULL) {
  $this->constraints[$constraint_name] = $options;
  return $this;
}