在symfony表单类型中使用自定义约束/验证器 [英] Use a custom constraint/validator in symfony form type

查看:49
本文介绍了在symfony表单类型中使用自定义约束/验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在表单类型中使用自定义工作验证器,但出现此错误:

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

未为约束AppBundle \ Validator \ Constraints \ DnsContent配置默认选项

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.

感谢您的帮助

推荐答案

尝试

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

抛出ConstraintDefinitionException当您不传递关联数组,但getDefaultOption()返回null

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

这篇关于在symfony表单类型中使用自定义约束/验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆