ZF2 inputfilter doctrine NoObjectExists编辑对象无效 [英] ZF2 inputfilter doctrine NoObjectExists editing object does not validate

查看:257
本文介绍了ZF2 inputfilter doctrine NoObjectExists编辑对象无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So i got a ZF2 application, got a Form and a InputFilter in the InputFilter i have:

$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验证器说匹配的对象是发现它没有验证。
有没有解决这个问题?
或者我应该删除编辑表单上的验证器,并在插入副本时捕获异常?

works great, however when i edit a existing object and save it the NoObjectExists validator says a matching object is found so it doesn't validate. Is there a solution to this problem? Or should i just remove the validator on the edit form and catch the exception when a duplicate is inserted?

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

是同样的问题,但答案是只是删除验证器的编辑,这是不是一个解决办法。因为您仍然必须捕获插入副本时抛出的异常。我可以做到这一点没有问题,但是我要求的是一个解决方案,使其工作与NoObjectExists(否则使用这个验证器,如果我必须捕获重复的异常)

is the same issue but the answer is to just remove the validator on editing, this off-course is not a solution. As you would still have to catch the exception thrown for when inserting a duplicate. I could do that no problem but what im asking for is a solution to make it work WITH NoObjectExists (otherwise whats the use of this validator if i have to catch the exception for duplicates anyway)

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

UPDATE, added other relevant code (my form and entity have more fields than this but i removed them to keep it readable on here)

FORM: p>

FORM:

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',
            ),
        )
    );

}
}

FILTER:

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'
                    ),
                ),
            ),
        )
    );
}
}

控制器操作:

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
    );
}

ENTITY:

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 .com /rel =nofollow> Github 。

I lately had the same issue on my project, I spend lot of time searching for a solution and I've finally found this module LosBase on Github.

它使用两个海关验证器,它们扩展 DoctrineModule\Validator\NoObjectExists NoEntityExists 添加操作和 NoOtherEntityExists for Edit action。

It uses two customs validators which extend DoctrineModule\Validator\NoObjectExists : NoEntityExists for Add action and NoOtherEntityExists for Edit action.

所以我用这个appraoch来解决我的问题。这是迄今为止所做的解决方案:

So I used this appraoch to resolve my problem. This is the solution I've made so far :

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验证器: / p>

NoEntityExists validator :

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一起使用: strong>

Using this validators with inputFilter :

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

In my custom input filters, I added two methods : one to append the NoEntityExists validator, and the other to append the NoOtherEntityExists validator :

/**
 * 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;
}

控制器:

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));

希望这可以帮助某人!

这篇关于ZF2 inputfilter doctrine NoObjectExists编辑对象无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆