ZF2输入过滤器原则NoObjectExists编辑对象不验证



所以我有一个ZF2应用程序,在InputFilter中有一个Form和一个InputFilter:

$this->add(
array(
'name'       => 'email',
'required'   => true,
'validators' => array(
array(
'name' => 'EmailAddress'
),
array(
'name'      => 'DoctrineModuleValidatorNoObjectExists',
'options' => array(
'object_repository' => $sm->get('doctrine.entitymanager.orm_default')->getRepository('YrmUserEntityUser'),
'fields'            => 'email'
),
),
),
)
);

工作得很好,但是当我编辑一个现有对象并保存它时,NoObjectExists验证器会说找到了一个匹配的对象,所以它不会进行验证。这个问题有解决办法吗?还是应该删除编辑表单上的验证器,并在插入重复项时捕获异常?

更新:如何在编辑表单中使用DoctrineModule\Validator\NoObjectExists-Zend Framework 2&条令2

是相同的问题,但答案是在编辑时删除验证器,这不是一个解决方案。因为在插入重复项时,您仍然必须捕获为引发的异常。我可以做到这一点,没有问题,但我所要求的是一个解决方案,使其与NoObjectExists一起工作(否则,如果我无论如何都必须捕捉重复的异常,这个验证器有什么用)

UPDATE,添加了其他相关代码(我的表单和实体有更多的字段,但我删除了它们,以保持其在此处的可读性)

形式:

namespace YrmUserForm;
use ZendFormForm;
use DoctrineModuleStdlibHydratorDoctrineObject as DoctrineHydrator;
use DoctrineORMModuleStdlibHydratorDoctrineEntity;
use YrmUserEntityUser;

class UserForm extends Form
{
protected $objectManager;
/**
* __construct description
*
* @param String $name form name
* 
* @return void
*/
public function __construct($name = null)
{
parent::__construct('new-user');
}
public function init()
{
$this->setHydrator(
new DoctrineHydrator($this->objectManager, 'YrmUserEntityUser')
)->setObject(new User());
$this->setAttribute('method', 'post');

$this->add(
array(
'name' => 'email',
'attributes' => array(
'type'  => 'email',
'placeholder' =>'Email',
),
'options' => array(
'label' => 'Email',
),
)
);
}
}

过滤器:

class UserFilter extends InputFilter
{
/**
* [__construct description]
* 
* @param ServiceLocator $sm servicelocator
*/
public function __construct($sm)
{

$this->add(
array(
'name'       => 'email',
'required'   => true,
'validators' => array(
array(
'name' => 'EmailAddress'
),
array(
'name'      => 'DoctrineModuleValidatorNoObjectExists',
'options' => array(
'object_repository' => $sm->get('doctrine.entitymanager.orm_default')->getRepository('YrmUserEntityUser'),
'fields'            => 'email'
),
),
),
)
);
}
}

控制器动作:

public function editAction() 
{
$id = (int) $this->params('id', null);
if (null === $id) {
return $this->redirect()->toRoute('manage-users');
}
$em = $this->getServiceLocator()->get('DoctrineORMEntityManager');
$formManager = $this->getServiceLocator()->get('FormElementManager');
$form = $formManager->get('UserForm');
$user = $em->find('YrmUserEntityUser', $id);
$form->setInputFilter(new UserFilter($this->getServiceLocator()));
$form->bind($user);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$em->persist($user);
$em->flush();
return $this->redirect()->toRoute('manage-users');
}
}
return array(
'form' => $form,
'id' => $id
);
}

实体:

class User
{
/**
* @var int
* @ORMId
* @ORMColumn(type="integer")
* @ORMGeneratedValue(strategy="AUTO")
*/
protected $id;

/**
* @var string
* @ORMColumn(type="string", unique=true,  length=255)
*/
protected $email;

/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* @param int $id user id
*
* @return void
*/
public function setId($id)
{
$this->id = (int) $id;
}

/**
* Get email.
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email.
*
* @param string $email user email adress
*
* @return void
*/
public function setEmail($email)
{
$this->email = $email;
}
}

提前感谢

Yrm

我最近在我的项目中遇到了同样的问题,我花了很多时间寻找解决方案,终于找到了这个模块LosBase。

它使用两个海关验证器,它们扩展了DoctrineModuleValidatorNoObjectExists:NoEntityExists用于Add操作,NoOtherEntityExists用于Edit操作。

所以我用这个学徒来解决我的问题。这是我迄今为止制定的解决方案:

NoOtherEntityExists验证器:

use ZendValidatorExceptionInvalidArgumentException;
use DoctrineModuleValidatorNoObjectExists;
class NoOtherEntityExists extends NoObjectExists
{
private $id; //id of the entity to edit
private $id_getter;  //getter of the id
private $additionalFields = null; //other fields
public function __construct(array $options)
{
parent::__construct($options);
if (isset($options['additionalFields'])) {
$this->additionalFields = $options['additionalFields'];
}
$this->id = $options['id'];
$this->id_getter = $options['id_getter'];
}
public function isValid($value, $context = null)
{
if (null != $this->additionalFields && is_array($context)) {
$value = (array) $value;
foreach ($this->additionalFields as $field) {
$value[] = $context[$field];
}
}
$value = $this->cleanSearchValue($value);
$match = $this->objectRepository->findOneBy($value);
if (is_object($match) && $match->{$this->id_getter}() != $this->id) {
if (is_array($value)) {
$str = '';
foreach ($value as $campo) {
if ($str != '') {
$str .= ', ';
}
$str .= $campo;
}
$value = $str;
}
$this->error(self::ERROR_OBJECT_FOUND, $value);
return false;
}
return true;
}
}

NoEntityExists验证器:

use ZendValidatorExceptionInvalidArgumentException;
use DoctrineModuleValidatorNoObjectExists;
class NoEntityExists extends NoObjectExists
{
private $additionalFields = null;
public function __construct(array $options)
{
parent::__construct($options);
if (isset($options['additionalFields'])) {
$this->additionalFields = $options['additionalFields'];
}
}
public function isValid($value, $context = null)
{
if (null != $this->additionalFields && is_array($context)) {
$value = (array) $value;
foreach ($this->additionalFields as $field) {
$value[] = $context[$field];
}
}
$value = $this->cleanSearchValue($value);
$match = $this->objectRepository->findOneBy($value);
if (is_object($match)) {
if (is_array($value)) {
$str = '';
foreach ($value as $campo) {
if ($str != '') {
$str .= ', ';
}
$str .= $campo;
}
$value = $str;
}
$this->error(self::ERROR_OBJECT_FOUND, $value);
return false;
}
return true;
}
}

将此验证器与inputFilter一起使用:

在我的自定义input filters中,我添加了两种方法:一种是附加NoEntityExists验证器,另一种是添加NoOtherEntityExists验证器:

/**
* Appends doctrine's NoObjectExists Validator for Add FORM .
*
* @param DoctrineORMEntityRepository $repository
* @return ZendInputFilterInputFilter
*/
public function appendAddValidator(EntityRepository $repository)
{
$this->add($this->getFactory()->createInput( array(
'name' => 'libellesite', //unique field name
'validators' => array(
array(
'name' => 'NetmanFormNoEntityExists',//use namespace
'options' => array(
'object_repository' => $repository,
'fields' => 'libellesite',
'messages' => array(
'objectFound' => 'custom message here'
),
),
),
)
)));
return $this;
}
/**
* Appends doctrine's NoObjectExists Validator for EDIT FORM.
*
* @param DoctrineORMEntityRepository $repository
* @return ZendInputFilterInputFilter
*/
public function appendEditValidator(EntityRepository $repository, $id)
{
$this->add($this->getFactory()->createInput( array(
'name' => 'libellesite',
'validators' => array(
array(
'name' => 'NetmanFormNoOtherEntityExists',
'options' => array(
'object_repository' => $repository,
'fields' => 'libellesite',
'id'=>$id, //
'id_getter'=>'getCodesite',//getter for ID
'messages' => array(
'objectFound' => 'custom message here'
),
),
),
)
)));
return $this;
}

控制器:

addAction:中

$repository = $em->getRepository('EntityName');  
$form->setInputFilter($filter->appendAddValidator($repository));

editAction:中

$id = $this->params('id', null);
$repository = $em->getRepository('EntityName');  
$form->setInputFilter($filter->appendEditValidator($repository,$id));

相关内容

  • 没有找到相关文章

最新更新