首页 文章

没有调用Symfony 2实体验证回调

提问于
浏览
2

有人可以帮我弄清楚为什么我的Callback验证方法没有被调用 .

基本上我需要做的是使用以下逻辑的自定义验证: - 在表单中我有5个字段,如果全部为空,表单应该是有效的, - 但是如果任何不是空的,则所有这些都不需要为空(它们用于在用户配置文件上构建真实地址)

我关注了以下文档:http://symfony.com/doc/2.3/reference/constraints/Callback.html

我有以下代码:

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="UserRepository");
 * @UniqueEntity("email")
 * @ORM\HasLifecycleCallbacks
 * @Assert\Callback(methods={"isAddressValid"})
 */
class User extends WebserviceUser implements UserInterface, EquatableInterface
{
...

    public function isAddressValid(ExecutionContextInterface $context)
    {
        //die("I GOT HERE");
        $context->addViolationAt('sna4', 'Frikin validation'!', array(), null);
    }
}

属性sna4在被扩展的类中找到 .

先感谢您 .

1 回答

  • 4

    回调注释需要(如果有任何定义)关联的验证组 .

    作为示例,在不同的表单上下文中使用的实体具有特定表单的验证自定义:

    The Entity Class:

    /**
     *
     * @Assert\Callback(methods={"validateCommunicationEmail"}, groups={"userProfile"})
     * @Assert\Callback(methods={"validatePreference"}, groups={"userPreference"})
     */
    class AcmePreferences
    {
    
        ....
    
            public function validateCommunicationEmail(ExecutionContextInterface $context)
        {
            if ($this->getIsCommunicationsEnabled() && ! $this->getAdministrativeCommunicationEmail())
            {
                $context->addViolationAt('isCommunicationsEnabled','error.no_administrative_email_selected');
            }
    
        }
    
    }
    

    The Form Type:

    class AcmePreferencesType extends AbstractType
    {
    
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'data_class'=> 'Acme\DemoBundle\Entity\AcmePreferences',
                'validation_groups' => array('userProfile')
            ));
        }
    

相关问题