我在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