2

I have created custom type field with custom field settings, attached custom constraint successfully called its validator.

The question how to get the field settings values in the validate function, below code sample may explain

/**
 * Validates the CustomCheckConstraint.
*/
class CustomCheckConstraintValidator extends ConstraintValidator {
 protected $context;
 public function validate($data, Constraint $constraint) {
   //$data parameter holds the field value 
   //how could I get the field settings here and validate the value based on
}
}

//attached constraint here 
public static function    propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('integer')
  ->setLabel(t('type'))
  ->addConstraint('CustomCheck')
  ->setRequired(TRUE);
return $properties;

}

Edit: After berdir answer

now the $data variable is an object holds the whole filedType object value and settings.

The problem is I couldn't get the field settings from getSettings() function returns

Error: Call to protected method

The same error occurs when I tried to send field settings value from propertyDefinitions function

1 Answer 1

4

If they are field storage settings, then you could pass them along as arguments to the constraint.

If not, then add the constraint on the field type, not on the property. You can do that directly in the annotation, see \Drupal\file\Plugin\Field\FieldType\FileItem as an exampe. Then you get the whole field item in your validator and you can access the values and the definition/settings.

1
  • Thanks Berdir, now the $data variable is an object holds the whole filedType object value and settings. The problem is I couldn't get the field settings from getSettings() function returns Error: Call to protected method Commented Aug 22, 2016 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.