I have created custom field type with custom constraint defined and called successfully, the question is how to send the field settings to my constraint in the code block below.
/**
* Plugin implementation of the 'custom_field_type' field type.
*
* @FieldType(
* id = "custom_field_type",
* label = @Translation("custom field type"),
* description = @Translation("custom field type"),
* default_widget = "number",
* default_formatter = "number_integer"
* )
*/
class CustomFieldType extends IntegerItem {
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return array(
'type' => array(
'#type' => 'radios',
'#title' => t('type Validator'),
'#default_value' => 'none',
'#options' => [],
'#description' => t('types.'),
),
) + parent::defaultFieldSettings();
}
/**
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$type_options = array(
'type1' => t('type1'),
'type2' => t('type2'),
'none' => t('type1 and type2'),
);
return array(
'type' => array(
'#type' => 'radios',
'#title' => t('type Validator'),
'#default_value' => $this->getSetting('type'),
'#options' => $type_options,
'#description' => t('types.'),
),
);
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('integer')
->setLabel(t('type'))
->addConstraint('CustomCheck')
->setRequired(TRUE);
return $properties;
}
}
How to send the field settings as arguments to the constraint as the validation only takes the field value as parameter.
/**
* Validates the CustomCheckConstraint.
*/
class CustomCheckConstraintValidator extends ConstraintValidator {
/**
* Validator 2.5 and upwards compatible execution context.
*
* @var \Symfony\Component\Validator\Context\ExecutionContextInterface
*/
protected $context;
public function validate($data, Constraint $constraint) {
//do custom check here
}
}