Change record status: 
Project: 
Introduced in branch: 
8.7.x
Introduced in version: 
8.7.0
Description: 

ContextDefinition objects can have constraints added to them, see \Drupal\Component\Plugin\Context\ContextDefinitionInterface::addConstraint()
Since the majority of properties of ContextDefinition are specified by its constructor, it was possible to provide values for those within the @ContextDefinition annotation.

Constraints now can be added directly within the annotation as well.

Before

/**
 * @Block(
 *   id = "my_block",
 *   context_definitions = {
 *     "entity" = @ContextDefinition("entity"),
 *   }
 * )
 */
class MyBlock extends BlockBase {
 // ...
}

// In .module file:
function mymodule_block_alter(array &$definitions) {
  $definitions['myblock']['context_definitions']['entity']->addConstraint('MyConstraint', 'my_constraint_option');
}

After


/**
 * @Block(
 *   id = "my_block",
 *   context_definitions = {
 *     "entity" = @ContextDefinition("entity", constraints = {
 *       "MyConstraint" = "my_constraint_option",
 *     }),
 *   }
 * )
 */
class MyBlock extends BlockBase {
 // ...
}
Impacts: 
Module developers