【发布时间】:2013-11-14 10:15:35
【问题描述】:
我有一个带有断言回调方法“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;
}
}
【问题讨论】:
-
试试
$context->getViolations()。它返回到目前为止的所有违规行为 -
我试过了,但是当约束不满足时,它返回一个空数组。
-
你是对的,但我认为这是检查约束是否成功的唯一方法。尝试触发用户名和密码约束并检查数组是否为空。您可以使用 var_dump 和 die 的 Xdebug 来做到这一点 :)
标签: symfony callback symfony-2.1 validation