1

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
}
}

1 Answer 1

0

The method addConstraint allows an optional array of options to be passed to the constraint plugin. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21TypedData%21DataDefinition.php/function/DataDefinition%3A%3AaddConstraint/8.2.x

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.