我在学习教义,我有一个表格。 ZF2 和带有字段“电子邮件”的学说。 这个字段需要是唯一的,所以我需要它的验证器。我也在使用字段集(这在这里很重要)。问题是,当我使用时:
DoctrineModule\Validator\UniqueObject
不可能创建新实体。该验证器需要主键进行比较。 验证器转储错误消息:
Expected context to contain itemId
itemId 是我的主键。
很明显,我需要使用 UniqueObject 进行更新,并且:
DoctrineModule\Validator\NoObjectExists
对于新实体。问题是:
为现有实体和新实体存储不同输入过滤器规范的最佳方法是什么?
或者,如果可能的话更好:How to use Unique validator with new, and existing records with zend form fieldsets。
如果我把它放在表单中,如果实体是新的或不是,我需要在 Controller 内部修改它。不是什么好主意。
我认为最好的方法是存储输入过滤器规范。在实体存储库中,但是我如何检查实体是否是新的?
----编辑
我看过文档,我知道如何使用唯一对象,但我遇到了如前所述的错误:“预期上下文包含 itemId”。我认为问题出在字段集上(我正在使用它)。我不明白该怎么做(文档中的文本):
If you leave out the use_context option or set it to false you have to pass an array containing the fields- and identifier-values into isValid(). When using Zend\Form this behaviour is needed if you're using fieldsets.
好的,我正在使用字段集,那么现在我能做什么?我如何在使用 zend 表单时将正确的值传递给 isValid?
最佳答案
使用 UniqueObject
验证器,您需要在上下文中包含标识符字段。所以它只有在 email
列是您的 Email
实体的标识符列时才有效?您有一个额外的 id
列。最好在您的用户案例中使用 NoObjectExists
验证器:
'email' => array(
'validators' => array(
array(
'name' => 'DoctrineModule\Validator\NoObjectExists',
'options' => array(
'object_repository' => $entityManager->getRepository(
'Application\Entity\Email'
),
'fields' => 'email'
)
)
)
)
你也可以找到这个例子in the documentation .
编辑
关于分离更新和新输入过滤器的逻辑,我建议创建两个文件夹。最好像那样严格分开,否则很可能会出错。例如,您可以这样做(但这完全取决于您个人的喜好,这是如何组织的)。
Application/InputFilter/Create
UserInputFilter
还有一个用于更新资源:
Application/InputFilter/Update
UserInputFilter
然后在你的 Controller 中你可以这样做:
<?php
namespace Application\Controller;
use Application\InputFilter\Create;
use Application\InputFilter\Update;
class UserController{
public function updateAction()
{
$inputFilter = new Update\UserInputFilter();
//... etc
}
public function createAction()
{
$inputFilter = new Create\UserInputFilter();
//... etc
}
}
关于php - ZF2 和 Doctrine 输入过滤器(Unique,ObjectExists),用于具有字段集的新实体和现有实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33452154/