我在Symfony2中创建表单。该表格仅包含一个book
字段,该字段允许用户在Books
实体列表中进行选择。我需要检查所选的Book
是否属于我的控制器中的Author
。将自定义参数传递给Symfony2中的自定义ValidationConstraint
我要检查,提交表单后,所选择的Book
由$author
在我的控制器写:
public class MyController
{
public function doStuffAction() {
$author = ...;
$form = $this->createForm(new MyFormType($author));
$form->bind($this->getRequest());
// ...
}
}
不幸的是,我无法找到任何方式做到这一点。我试图创建一个自定义的验证器约束,如The Cookbook中所解释的,但虽然我可以通过将EntityManager
作为参数将验证器定义为服务,但我无法将$author
从控制器传递到验证器约束。
class HasValidAuthorConstraintValidator extends ConstraintValidator
{
private $entityManager;
public function __construct(EntityManager $entityManager) {
$this->entityManager = $entityManager;
}
public function validate($value, Constraint $constraint) {
$book = $this->entityManager->getRepository('book')->findOneById($value);
$author = ...; // That's the data I'm missing
if(!$book->belongsTo($author))
{
$this->context->addViolation(...);
}
}
}
This solution可能正是我一直在寻找的人,但我的形式不绑定到一个实体,并不意味着是(我收到来自getData()
方法中的数据)。
有没有解决我的问题?这一定是常见的情况,但我真的不知道如何解决它。
请注意,在Symfony 2.7中,自定义参数不是直接在$ options数组中找到的,而是在“值”键内。所以对于这个例子,你会从$ options ['value'] ['author']得到作者。如果您使用注释声明断言,您可以编写如下内容: @CustomAssert \ CustomDateTime({“dateFormat”:Enum :: DATE_FORMAT}) – 2016-09-28 07:07:24