1

我有一个带有断言回调方法“processSignup”的实体帐户。仅当登录约束和密码约束成功时,我才想调用“processSignup”。请问如何在我的 processSignup 方法中检查这个?

<?php
namespace MyProject\Bundle\FrontBundle\Entity;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Assert\Callback(methods={"processSignup"})
 */
class Account
{

    /**
     * @Assert\NotBlank()
     * @Assert\Type(type="string")
     * @Assert\Length(min = 6, max = 16)
     */
    protected $login;

    /**
     * @Assert\NotBlank()
     * @Assert\Type(type="string")
     * @Assert\Length(min = 8, max = 12)
     */
    protected $password;

    /**
     * @param ExecutionContext $context
     */
    public function processSignup(ExecutionContext $context)
    {
        // if login and password constraints success, do something
    }

    public function getLogin()
    {
        return $this->login;
    }

    public function setLogin($login)
    {
        $this->login = $login;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }
}
4

1 回答 1

2

在同样的情况下,我使用了验证组:

/** @Assert\Callback(methods={"processSignup"}, groups={"LastValidation"}) */
class Account {
    /**
     * @Assert\NotBlank()
     * @Assert\Type(type="string")
     * @Assert\Length(min = 6, max = 16)
     */
    protected $login;
....
}

在 FormType 中:

class AccountType extends AbstractType {
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
       ....
   }

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    parent::setDefaultOptions($resolver);
    $resolver->setDefaults(
            [
            ....
            'validation_groups' => function (FormInterface $form)
                    {
                        return ['Account', 'LastValidation'];
                        // The first element's value must be the same as data-class name
                    }
            ]
    );

}

然后在 processSignup 方法中你可以检查

    if(0 !== $context->getViolations()->count())
    {
        return;
    }
于 2013-11-15T13:22:39.177 回答