gpt4 book ai didi

doctrine-orm - ZF2 inputfilter 主义 NoObjectExists 编辑对象不验证

转载 作者:行者123 更新时间:2023-12-02 21:39:33 25 4
gpt4 key购买 nike

所以我得到了一个 ZF2 应用程序,在我拥有的 InputFilter 中得到了一个 Form 和一个 InputFilter:

$this->add(
array(
'name' => 'email',
'required' => true,
'validators' => array(
array(
'name' => 'EmailAddress'
),
array(
'name' => 'DoctrineModule\Validator\NoObjectExists',
'options' => array(
'object_repository' => $sm->get('doctrine.entitymanager.orm_default')->getRepository('YrmUser\Entity\User'),
'fields' => 'email'
),
),
),
)
);

效果很好,但是当我编辑现有对象并保存它时,NoObjectExists 验证器表示找到了匹配的对象,因此无法验证。这个问题有解决办法吗?或者我应该删除编辑表单上的验证器并在插入重复项时捕获异常?

更新: How to use DoctrineModule\Validator\NoObjectExists in edit forms - Zend Framework 2 & Doctrine 2

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

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

表格:

namespace YrmUser\Form;

use Zend\Form\Form;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use DoctrineORMModule\Stdlib\Hydrator\DoctrineEntity;

use YrmUser\Entity\User;



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, 'YrmUser\Entity\User')
)->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' => 'DoctrineModule\Validator\NoObjectExists',
'options' => array(
'object_repository' => $sm->get('doctrine.entitymanager.orm_default')->getRepository('YrmUser\Entity\User'),
'fields' => 'email'
),
),
),
)
);
}
}

Controller 操作:

public function editAction() 
{
$id = (int) $this->params('id', null);
if (null === $id) {
return $this->redirect()->toRoute('manage-users');
}

$em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');

$formManager = $this->getServiceLocator()->get('FormElementManager');
$form = $formManager->get('UserForm');

$user = $em->find('YrmUser\Entity\User', $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
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;



/**
* @var string
* @ORM\Column(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 .

它使用两个自定义验证器,它们扩展了DoctrineModule\Validator\NoObjectExists:NoEntityExists用于Add操作和NoOtherEntityExists 用于 Edit 操作。

所以我用这个方法来解决我的问题。这是我到目前为止所做的解决方案:

NoOtherEntityExists 验证器:

use Zend\Validator\Exception\InvalidArgumentException;
use DoctrineModule\Validator\NoObjectExists;

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 Zend\Validator\Exception\InvalidArgumentException;
use DoctrineModule\Validator\NoObjectExists;

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 结合使用:

在我的自定义输入过滤器中,我添加了两种方法:一种用于附加 NoEntityExists 验证器,另一种用于附加 NoOtherEntityExists 验证器:

/**
* Appends doctrine's NoObjectExists Validator for Add FORM .
*
* @param \Doctrine\ORM\EntityRepository $repository
* @return \Zend\InputFilter\InputFilter
*/
public function appendAddValidator(EntityRepository $repository)
{
$this->add($this->getFactory()->createInput( array(
'name' => 'libellesite', //unique field name
'validators' => array(
array(
'name' => 'Netman\Form\NoEntityExists',//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 \Doctrine\ORM\EntityRepository $repository
* @return \Zend\InputFilter\InputFilter
*/
public function appendEditValidator(EntityRepository $repository, $id)
{
$this->add($this->getFactory()->createInput( array(
'name' => 'libellesite',
'validators' => array(
array(
'name' => 'Netman\Form\NoOtherEntityExists',
'options' => array(
'object_repository' => $repository,
'fields' => 'libellesite',
'id'=>$id, //
'id_getter'=>'getCodesite',//getter for ID
'messages' => array(
'objectFound' => 'custom message here'
),
),
),
)
)));
return $this;
}

Controller :

addAction中:

$repository = $em->getRepository('Entity\Name');  
$form->setInputFilter($filter->appendAddValidator($repository));

editAction中:

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

关于doctrine-orm - ZF2 inputfilter 主义 NoObjectExists 编辑对象不验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20680700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com