2
votes

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

1 Answers

4
votes

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])