2

I'm trying to use a custom working validator in my form type but I get this error :

No default option is configured for constraint AppBundle\Validator\Constraints\DnsContent

I have made this constraint + validator :

// My constraint
/**
 * @Annotation
 */
class DnsContent extends Constraint
{
    public $message = 'fail';

    /**
     * {@inheritdoc}
     */
    public function validatedBy()
    {
         return 'dns_content';
    }
}

// My validator
class DnsContentValidator extends ConstraintValidator
{
    public function validate($type, Constraint $constraint)
    {
        switch ($type) {
            case 'A':
                return new Assert\Ip(['version' => '4']);
                break;
            case 'AAAA':
                return new Assert\Ip(['version' => '6']);
                break;
            case 'CNAME':
            case 'NS':
            case 'MX':
                return new Assert\Regex(['pattern' => '/^[[:alnum:]-\._]+$/u']);
                break;
            default:
                return false;
                break;
        }
    }
}

I'm trying to use it inside my form type like this

$contentConstraints = function (FormInterface $form, $type) {
    $form->add('content', null, [
        'label'                 => 'form.content',
        'translation_domain'    => 'global',
        'constraints'           => new DnsContent($type),
    ]);
};

But I get the error I write above. I don't understand how to fix this and if I use the correct way to use a custom constraint validator in a form type.

Thanks for your help

1 Answer 1

4

Try

  $form->add('content', null, [
        'label'                 => 'form.content',
        'translation_domain'    => 'global',
        'constraints'           => new DnsContent(),
    ]);

throws ConstraintDefinitionException When you don't pass an associative array, but getDefaultOption() returns null

You can add custom options as constraint fields

class DnsContent extends Constraint

    {
        public $message = 'fail';

        public $type;

        /**
         * {@inheritdoc}
         */
        public function validatedBy()
        {
             return 'dns_content';
        }
    }

And now you can pass this options in array

new DnsContent(['type' => $type])
Sign up to request clarification or add additional context in comments.

4 Comments

I don't have the error anymore but my validator is not used
valdate method does not called?
Hum yes but I need to pass a type to use my switch case
The $type class variable gets assigned automatically from options associative array

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.