我有一个带有Assert Callback方法的实体帐户“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;
}
}
答案 0 :(得分:1)
在同样的情况下,我使用了验证组:
/** @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;
}