如何在ZF2中创建表单输入/元素 [英] How to create form inputs/elements in ZF2

查看:101
本文介绍了如何在ZF2中创建表单输入/元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我的主要问题现在已经变成如何使用教学实体管理器将ServiceManager与我的窗体,元素和输入类的手段以一些干净的方式进行交互?请阅读完整的帖子。 / p>

我要尝试这样的例子,这样忍受我。让我知道我在哪里出错/正确或可以改进的地方



我正在尝试创建一个注册表单。我可以使用ZfcUser模块,但我想自己做这个。我正在使用ZF2与Doctrine2,以便我远离那个模块。



我的策略是这样,


  1. 创建一个名为注册表单


  2. 为每个元素为每个元素创建独立的元素类,每个元素将具有输入规范


  3. 由于每个元素是单独的类,我可以单独测试每个元素。


一切似乎很好,直到我想添加一个验证器到我的用户名元素,将检查用户名不是使用。



以下是到目前为止的代码

  namepsace My\Form ; 

使用Zend\Form\Form,
Zend\Form\Element,
Zend\InputFilter\Input,
Zend\InputFilter\\ \\InputFilter,

/ **
*类名:注册
* /
类注册
扩展表单
{

const USERNAME ='username';
const EMAIL ='email';
const PASSWORD ='password';
const PASS_CONFIRM ='passwordConfirm';
const GENDER ='gender';
const CAPTCHA ='captcha';
const CSRF ='csrf';
const SUBMIT ='submit';

private $ captcha ='dumb';

public function prepareForm()
{
$ this-> setName('registration');

$ this-> setAttributes(array(
'method'=>'post'
));

$ this-> add(array(
'name'=> self :: USERNAME,
'type'=>'\My\Form\\ \\ element\UsernameElement',
'attributes'=>数组(
'label'=>'用户名',
'autofocus'=>'autofocus'


);

$ this-> add(array(
'name'=> self :: SUBMIT,
'type'=>'\Zend\Form\\ \\ element\Submit',
'attributes'=>数组(
'value'=>'提交'

));

}

}

我删除了很多,我认为没有必要。以下是我的用户名元素。

 命名空间My\Form\Registration; 

使用My\Validator\UsernameNotInUse;
使用Zend\Form\Element\Text,
Zend\InputFilter\InputProviderInterface,
Zend\Validator\StringLength,
Zend\Validator\ NotEmpty,
Zend\I18n\Validator\Alnum;

/ **
*
* /
class UsernameElement
extends Text
implements InputProviderInterface
{

private $ minLength = 3;
private $ maxLength = 128;

public function getInputSpecification()
{
return array(
'name'=> $ this-> getName(),
'required '=> true,
'filters'=> array(
array('name'=>'StringTrim')
),
'validators'=>
数组(
new NotEmpty(
array('mesages'=>
数组(
NotEmpty :: IS_EMPTY =>'您提供的用户名为空) '


),
new AlNum(array(
'messages'=>数组(Alnum :: STRING_EMPTY =>'用户名只能包含字母和数字')

),
new StringLength(
array(
'min'=> $ this-> getMinLength(),
'max'=> $ this-> getMaxLength(),
'messages'=>
数组(
StringLength :: TOO_LONG =>'用户名太长,不能超过'。$ this-> getMaxLength()。'characters。',
StringLength :: TOO_SHORT =>'用户名太短,不能短于'$ this-> getMinLength()。''。
StringLength :: INVALID =>'用户名不是有效..它必须在'。$ this-> getMinLength()。'和'。$ this-> getMaxLength()。'characters long。',


),
数组(
'name'=>'\My\Validator\UsernameNotInUse',
'options'=>数组(
' '=> array(
UsernameNotInUse :: ERROR_USERNAME_IN_USE =>'The usarn ame%value%已被其他用户使用'




);
}
}

现在这里是我的验证器

 命名空间My\Validator; 

使用My\Entity\Helper\User作为UserHelper,
My\EntityRepository\User作为UserRepository;
使用Zend\Validator\AbstractValidator,
Zend\ServiceManager\ServiceManagerAwareInterface,
Zend\ServiceManager\ServiceLocatorAwareInterface,
Zend\ServiceManager\ServiceManager;

/ **
*
* /
class UsernameNotInUse
extends AbstractValidator
implements ServiceManagerAwareInterface
{

const ERROR_USERNAME_IN_USE ='usernameUsed';

private $ serviceManager;

/ **
*
* @var UserHelper
* /
private $ userHelper;
protected $ messageTemplates = array(
UsernameNotInUse :: ERROR_USERNAME_IN_USE =>'您指定的用户名已被使用'
);

public function isValid($ value)
{
$ inUse = $ this-> getUserHelper() - > isUsernameInUse($ value);
if($ inUse)
{
$ this-> error(UsernameNotInUse :: ERROR_USERNAME_IN_USE,$ value);
}

return!$ inUse;
}

public function setUserHelper(UserHelper $ mapper)
{
$ this-> userHelper = $ mapper;
return $ this;
}

/ **
* @return My\EntityRepository\User
* /
public function getUserHelper()
{
if($ this-> userHelper == null)
{
$ this-> setUserHelper($ this-> getServiceManager() - > get('doctrine.entitymanager。 orm_default') - > getObjectRepository('My\Entity\User'));
}
return $ this-> userHelper;
}

public function setServiceManager(ServiceManager $ serviceManager)
{
echo get_class($ serviceManager);
echo var_dump($ serviceManager);
$ this-> serviceManager = $ serviceManager;
return $ this;
}

/ **
*
* @return ServiceManager
* /
public function getServiceManager()
{
return $ this-> serviceManager;
}

}

为什么这看起来好像想法给我?


  1. 似乎是一个很好的可测试性/重复使用选择,因为我可以在我的应用程序中单独重复使用元素如果需要的话。


  2. 我可以对每个元素生成的每个输入进行单元测试,以确保其正确接受/拒绝输入。


这是元素单元测试的例子

  public function testFactoryCreation()
{
$ fac = new Factory();

$ element = $ fac-> createElement(array(
'type'=>'\My\Form\Registration\UsernameElement'
)) ;
/ * @var $ element \My\Form\Registration\UsernameElement * /

$ this-> assertInstanceOf('\My\Form\Registration\\ \\ UsernameElement',
$ element);

$ input = $ fac-> getInputFilterFactory() - > createInput($ element-> getInputSpecification());
$ validators = $ input-> getValidatorChain() - > getValidators();
/ * @var $ validators \Zend\Validator\ValidatorChain * /

$ expectedValidators = array(
'Zend\Validator\StringLength',
'Zend\Validator\NotEmpty',
'Zend\I18n\Validator\Alnum',
'My\Validator\UsernameNotInUse'
);

foreach($ validators as $ validator)
{
$ actualClass = get_class($ validator ['instance']);
$ this-> assertContains($ actualClass,$ expectedValidators);

switch($ actualClass)
{
case'My\Validator\UsernameNotInUse':
$ helper = $验证器['instance'] - > getUserHelper();
// HAVING A PROBLEM HERE
$ this-> assertNotNull($ helper);
break;

默认值:

break;
}
}

}

我所得到的是,验证器无法正确获取UserHelper,这是一个来自doctrine的UserRepository。原因是因为验证器只能作为ServiceManager访问ValidatorPluginManager,而不能访问应用程序的ServiceManager。



我得到验证器的这个错误部分,虽然如果我在一般服务管理器上调用相同的get方法,它没有任何问题。

  1)Test\My\Form\Registration\UsernameElementTest :: testFactoryCreation 
Zend\ServiceManager \Exception\ServiceNotFoundException:Zend\ServiceManager\ServiceManager :: get无法获取或创建一个doctrine.entitymanager.orm_default的实例

验证器中的var_dump($ serviceManager)显示我是ValidatorPluginManager类。



我试过在service_manager中放一个工厂如下所示

 'service_manager'=>数组(
'工厂'=>数组(
'My\Validator\UsernameNotInUse'=> function($ sm)
{
$ validator = new \ My\Validator\UsernameNotInUse();
$ em = $ serviceManager-> get('doctrine.entitymanager.orm_default');
/ * @var $ em \Doctrine\ORM\\ \\ EntityManager * /
$ validator-> setUserHelper($ em-> getRepository('\My\Entity\User'));

return $ validator;
}

但是没有工作,因为它没有咨询应用程序级服务经理。



所以,总的来说,这是我的问题:


  1. <这种分离形式和元素的策略是一个好的策略吗?我应该继续努力吗?的方式?什么是替代方案?(为了可测试性,我打破了一些东西)我将仅测试表单本身与所有输入的组合,但似乎我也试图做


  2. 如何解决我以上的问题?


  3. 使用我看不到的其他方式的Zend的Form / Element / Input部分?



解决方案

这是我的验证器,使用静态方法注入entityManager并且与任何指令实体一起工作。

 <?php 

命名空间Base\Validator;

使用可遍历;
使用Zend\Stdlib\ArrayUtils;
使用Zend\Validator\AbstractValidator;
使用Doctrine\ORM\EntityManager;

class EntityUnique extends AbstractValidator
{
const EXISTS ='exists';

protected $ messageTemplates = array(
self :: EXISTS =>%%%%%%%%%%%%%%%%%%%

protected $ messageVariables = array(
'entity'=>'_entity',
'attribute'=>'_attribute',
);


protected $ _entity;
protected $ _attribute;
protected $ _exclude;

protected static $ _entityManager;

public static function setEntityManager(EntityManager $ em){

self :: $ _ entityManager = $ em;
}

public function getEntityManager(){

if(!self :: $ _ entityManager){

throw new \Exception (无实体主管礼);
}

return self :: $ _ entityManager;
}

public function __construct($ options = null)
{
if($ options instanceof Traversable){
$ options = ArrayUtils :: iteratorToArray ($令牌);
}

if(is_array($ options)){

if(array_key_exists('entity',$ options)){

$ this-> _entity = $ options ['entity'];
}

if(array_key_exists('attribute',$ options)){

$ this-> _attribute = $ options ['attribute'];
}

if(array_key_exists('exclude',$ options)){

if(!is_array($ options ['exclude'])||
!array_key_exists('attribute',$ options ['exclude'])||
!array_key_exists('value',$ options ['exclude'])){

throw新的\Exception('exclude选项必须包含属性和值键');
}

$ this-> _exclude = $ options ['exclude'];
}
}

parent :: __ construct(is_array($ options)?$ options:null);
}

public function isValid($ value,$ context = null)
{
$ this-> setValue($ value);

$ queryBuilder = $ this-> getEntityManager()
- > createQueryBuilder()
- > from($ this-> _entity,'e')
- > select('COUNT(e)')
- > where('e。'。$ this-> _attribute。'=:value')
- > setParameter ('value',$ this-> getValue());

if($ this-> _exclude){

$ queryBuilder = $ queryBuilder-> andWhere('e。'。$ this-> _exclude ['attribute ']。'!=:exclude')
- > setParameter('exclude',$ this-> _exclude ['value']);
}

$ query = $ queryBuilder-> getQuery();
if((integer)$ query-> getSingleScalarResult()!== 0){

$ this-> error(self :: EXISTS);
返回false;
}

return true;
}
}

ie。我正在使用它的表单元素,这些元素也经过测试,工作正常:

 <?php 

命名空间User\Form\Element;

使用Zend\Form\Element\Text;
使用Zend\InputFilter\InputProviderInterface;

类用户名扩展文本实现InputProviderInterface
{
public function __construct(){

parent :: __ construct('username');
$ this-> setLabel('Benutzername');
$ this-> setAttribute('id','username');
}

public function getInputSpecification(){

return array(
'name'=> $ this-> getName(),
'required'=> true,
'filters'=>数组(
数组(
'name'=>'StringTrim'
),
),
'validators'=> array(
array(
'name'=>'NotEmpty',
'break_chain_on_failure'=> true,
'options'=>数组(
'messages'=>数组(
'isEmpty'=>'Bitte geben Sie einen Benutzernamen ein。',
),
),
),
),
);
}
}

创建新用户时

 <?php 

命名空间User\Form\Element;

使用Zend\InputFilter\InputProviderInterface;
使用User\Form\Element\Username;

class CreateUsername extends Username implements InputProviderInterface
{
public function getInputSpecification(){

$ spec = parent :: getInputSpecification();
$ spec ['validators'] [] = array(
'name'=>'Base\Validator\EntityUnique',
'options'=>数组(
'message'=>'Der name%value%ist bereits vergeben。',
'entity'=>'User\Entity\User',
'attribute'=> 'username',
),
);

return $ spec;
}
}

在现有用户中编辑

 <?php 

命名空间User\Form\Element;

使用Zend\InputFilter\InputProviderInterface;
使用User\Form\Element\Username;

class EditUsername extends Username implements InputProviderInterface
{
protected $ _userId;

public function __construct($ userId){

parent :: __ construct();
$ this-> _userId =(integer)$ userId;
}

public function getInputSpecification(){

$ spec = parent :: getInputSpecification();
$ spec ['validators'] [] = array(
'name'=>'Base\Validator\EntityUnique',
'options'=>数组(
'message'=>'Der name%value%ist bereits vergeben。',
'entity'=>'User\Entity\User',
'attribute'=> 'username',
'exclude'=> array(
'attribute'=>'id',
'value'=> $ this-> _userId,
),
),
);

return $ spec;
}
}


EDIT : My main question has now become 'How do I get the ServiceManager with the doctrine entity manager into the hands of my form, element, and input classes in some clean way?' Read on to see the full post.

I'm going to try and ask by example here so bear with me. Let me know where I'm going wrong/right or where I could improve

I'm trying to create a registration form. I could use ZfcUser module but I want to do this on my own. I'm using ZF2 with Doctrine2 as well so that leads me away from that module a bit.

My strategy was this,

  1. Create a form class called registration form

  2. Create separate 'element' classes for each element where each element will have an input specification

  3. Since each element is a separate class from the form I can unit test each one separately.

All seemed fine until I wanted to add a validator to my username element that would check that the username is NOT is use yet.

Here is the code thus far

namepsace My\Form;

use Zend\Form\Form,
    Zend\Form\Element,
    Zend\InputFilter\Input,
    Zend\InputFilter\InputFilter,

/**
 * Class name : Registration
 */
class Registration
    extends Form
{

    const USERNAME     = 'username';
    const EMAIL        = 'email';
    const PASSWORD     = 'password';
    const PASS_CONFIRM = 'passwordConfirm';
    const GENDER       = 'gender';
    const CAPTCHA      = 'captcha';
    const CSRF         = 'csrf';
    const SUBMIT       = 'submit';

    private $captcha = 'dumb';

    public function prepareForm()
    {
        $this->setName( 'registration' );

        $this->setAttributes( array(
            'method' => 'post'
        ) );

        $this->add( array(
            'name'       => self::USERNAME,
            'type'       => '\My\Form\Element\UsernameElement',
            'attributes' => array(
                'label'     => 'Username',
                'autofocus' => 'autofocus'
            )
            )
        );

        $this->add( array(
            'name'       => self::SUBMIT,
            'type'       => '\Zend\Form\Element\Submit',
            'attributes' => array(
                'value' => 'Submit'
            )
        ) );

    }

}

I removed a lot that I think isn't necessary. Here is my username element below.

namespace My\Form\Registration;

use My\Validator\UsernameNotInUse;
use Zend\Form\Element\Text,
    Zend\InputFilter\InputProviderInterface,
    Zend\Validator\StringLength,
    Zend\Validator\NotEmpty,
    Zend\I18n\Validator\Alnum;

/**
 *
 */
class UsernameElement
    extends Text
    implements InputProviderInterface
{

    private $minLength = 3;
    private $maxLength = 128;

    public function getInputSpecification()
    {
        return array(
            'name'     => $this->getName(),
            'required' => true,
            'filters'  => array(
                array( 'name'       => 'StringTrim' )
            ),
            'validators' =>
            array(
                new NotEmpty(
                    array( 'mesages' =>
                        array(
                            NotEmpty::IS_EMPTY => 'The username you provided is blank.'
                        )
                    )
                ),
                new AlNum( array(
                    'messages' => array( Alnum::STRING_EMPTY => 'The username can only contain letters and numbers.' )
                    )
                ),
                new StringLength(
                    array(
                        'min'      => $this->getMinLength(),
                        'max'      => $this->getMaxLength(),
                        'messages' =>
                        array(
                            StringLength::TOO_LONG  => 'The username is too long. It cannot be longer than ' . $this->getMaxLength() . ' characters.',
                            StringLength::TOO_SHORT => 'The username is too short. It cannot be shorter than ' . $this->getMinLength() . ' characters.',
                            StringLength::INVALID   => 'The username is not valid.. It has to be between ' . $this->getMinLength() . ' and ' . $this->getMaxLength() . ' characters long.',
                        )
                    )
                ),
                array(
                    'name'    => '\My\Validator\UsernameNotInUse',
                    'options' => array(
                        'messages' => array(
                            UsernameNotInUse::ERROR_USERNAME_IN_USE => 'The usarname %value% is already being used by another user.'
                        )
                    )
                )
            )
        );
    }    
}

Now here is my validator

namespace My\Validator;

use My\Entity\Helper\User as UserHelper,
    My\EntityRepository\User as UserRepository;
use Zend\Validator\AbstractValidator,
    Zend\ServiceManager\ServiceManagerAwareInterface,
    Zend\ServiceManager\ServiceLocatorAwareInterface,
    Zend\ServiceManager\ServiceManager;

/**
 *
 */
class UsernameNotInUse
    extends AbstractValidator
    implements ServiceManagerAwareInterface
{

    const ERROR_USERNAME_IN_USE = 'usernameUsed';

    private $serviceManager;

    /**
     *
     * @var UserHelper
     */
    private $userHelper;
    protected $messageTemplates = array(
        UsernameNotInUse::ERROR_USERNAME_IN_USE => 'The username you specified is being used already.'
    );

    public function isValid( $value )
    {
        $inUse = $this->getUserHelper()->isUsernameInUse( $value );
        if( $inUse )
        {
            $this->error( UsernameNotInUse::ERROR_USERNAME_IN_USE, $value );
        }

        return !$inUse;
    }

    public function setUserHelper( UserHelper $mapper )
    {
        $this->userHelper = $mapper;
        return $this;
    }

    /**
     * @return My\EntityRepository\User
     */
    public function getUserHelper()
    {
        if( $this->userHelper == null )
        {
            $this->setUserHelper( $this->getServiceManager()->get( 'doctrine.entitymanager.orm_default' )->getObjectRepository( 'My\Entity\User') );
        }
        return $this->userHelper;
    }

    public function setServiceManager( ServiceManager $serviceManager )
    {
        echo get_class( $serviceManager );
        echo var_dump( $serviceManager );
        $this->serviceManager = $serviceManager;
        return $this;
    }

    /**
     *
     * @return ServiceManager
     */
    public function getServiceManager( )
    {
        return $this->serviceManager;
    }

}

Why did this seem like a good idea to me?

  1. It seemed like a good testability/re-use choice to make since I could re-use the elements separately across my application if need be.

  2. I could unit test each Input generated by each element to make sure it correctly accepts/rejects input.

This is the example of my unit test for the element

public function testFactoryCreation()
{
    $fac = new Factory();

    $element = $fac->createElement( array(
        'type' => '\My\Form\Registration\UsernameElement'
        ) );
    /* @var $element \My\Form\Registration\UsernameElement  */

    $this->assertInstanceOf( '\My\Form\Registration\UsernameElement',
                             $element );

    $input      = $fac->getInputFilterFactory()->createInput( $element->getInputSpecification() );
    $validators = $input->getValidatorChain()->getValidators();
    /* @var $validators \Zend\Validator\ValidatorChain */

    $expectedValidators = array(
        'Zend\Validator\StringLength',
        'Zend\Validator\NotEmpty',
        'Zend\I18n\Validator\Alnum',
        'My\Validator\UsernameNotInUse'
    );

    foreach( $validators as $validator )
    {
        $actualClass = get_class( $validator['instance'] );
        $this->assertContains( $actualClass, $expectedValidators );

        switch( $actualClass )
        {
            case 'My\Validator\UsernameNotInUse':
                $helper = $validator['instance']->getUserHelper();
                //HAVING A PROBLEM HERE
                $this->assertNotNull( $helper );
                break;

            default:

                break;
        }
    }

}

The problem I'm having is that the validator can't fetch the UserHelper properly, which is really a UserRepository from doctrine. The reason this is happening is because the validators only get access to the ValidatorPluginManager as a ServiceManager rather than having access to the application wide ServiceManager.

I get this error for the Validator portion, although if I call the same get method on the general service manager it works with no problems.

1) Test\My\Form\Registration\UsernameElementTest::testFactoryCreation
Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for doctrine.entitymanager.orm_default

The var_dump( $serviceManager ) in validator shows me it is of the class ValidatorPluginManager.

I tried putting a factory in the service_manager entry like so

'service_manager' => array(
                'factories' => array(
                    'My\Validator\UsernameNotInUse' => function( $sm )
                    {
                        $validator = new \My\Validator\UsernameNotInUse();
                        $em        = $serviceManager->get( 'doctrine.entitymanager.orm_default' );
                        /* @var $em \Doctrine\ORM\EntityManager */
                        $validator->setUserHelper( $em->getRepository( '\My\Entity\User' ) );

                        return $validator;
                    }
                )

but that didn't work because it's not consulting the application level service manager.

So, overall, here are my questions :

  1. Is this strategy of separating the form and elements a good one? Should I keep going this way? What are alternatives? ( I'm for breaking stuff up for the sake of testability ) I was going to test ONLY the form itself originally with a combination of ALL the inputs but it seemed like I'd be trying to do too much.

  2. How do I resolve the issue I have above?

  3. Should I be using the Form/Element/Input parts of Zend in some other way that I'm not seeing?

解决方案

this is my validator, using a static method to inject the entityManager and working with any doctine entity.

<?php

namespace Base\Validator;

use Traversable;
use Zend\Stdlib\ArrayUtils;
use Zend\Validator\AbstractValidator;
use Doctrine\ORM\EntityManager;

class EntityUnique extends AbstractValidator
{
    const EXISTS = 'exists';

    protected $messageTemplates = array(
        self::EXISTS => "A %entity% record already exists with %attribute% %value%",
    );

    protected $messageVariables = array(
        'entity' => '_entity',
        'attribute' => '_attribute',
    );


    protected $_entity;
    protected $_attribute;
    protected $_exclude;

    protected static $_entityManager;

    public static function setEntityManager(EntityManager $em) {

        self::$_entityManager = $em;
    }

    public function getEntityManager() {

        if (!self::$_entityManager) {

            throw new \Exception('No entitymanager present');
        }

        return self::$_entityManager;
    }

    public function __construct($options = null)
    {
        if ($options instanceof Traversable) {
            $options = ArrayUtils::iteratorToArray($token);
        }

        if (is_array($options)) {

            if (array_key_exists('entity', $options)) {

                $this->_entity = $options['entity'];
            }

            if (array_key_exists('attribute', $options)) {

                $this->_attribute = $options['attribute'];
            }

            if (array_key_exists('exclude', $options)) {

                if (!is_array($options['exclude']) ||
                    !array_key_exists('attribute', $options['exclude']) ||
                    !array_key_exists('value', $options['exclude'])) {

                    throw new \Exception('exclude option must contain attribute and value keys');
                }

                $this->_exclude = $options['exclude'];
            }
        }

        parent::__construct(is_array($options) ? $options : null);
    }

    public function isValid($value, $context = null)
    {
        $this->setValue($value);

        $queryBuilder = $this->getEntityManager()
            ->createQueryBuilder()
            ->from($this->_entity, 'e')
            ->select('COUNT(e)')
            ->where('e.'. $this->_attribute . ' = :value')
            ->setParameter('value', $this->getValue());

        if ($this->_exclude) {

            $queryBuilder = $queryBuilder->andWhere('e.'. $this->_exclude['attribute'] . ' != :exclude')
                ->setParameter('exclude', $this->_exclude['value']);
        }

        $query = $queryBuilder->getQuery();        
        if ((integer)$query->getSingleScalarResult() !== 0) {

            $this->error(self::EXISTS);
            return false;
        }

        return true;
    }
}

ie. i'm using it for theese form elements which are also tested and working fine:

<?php

namespace User\Form\Element;

use Zend\Form\Element\Text;
use Zend\InputFilter\InputProviderInterface;

class Username extends Text implements InputProviderInterface
{
    public function __construct() {

        parent::__construct('username');
        $this->setLabel('Benutzername');
        $this->setAttribute('id', 'username');
    }

    public function getInputSpecification() {

        return array(
            'name' => $this->getName(),
            'required' => true,
            'filters'  => array(
                array(
                    'name' => 'StringTrim'
                ),
            ),
            'validators' => array(
                array(
                    'name' => 'NotEmpty',
                    'break_chain_on_failure' => true,
                    'options' => array(
                        'messages' => array(
                            'isEmpty' => 'Bitte geben Sie einen Benutzernamen ein.',
                        ),
                    ),
                ),
            ),
        );
    }
}

When creating a new user

<?php

namespace User\Form\Element;

use Zend\InputFilter\InputProviderInterface;
use User\Form\Element\Username;

class CreateUsername extends Username implements InputProviderInterface
{
    public function getInputSpecification() {

        $spec = parent::getInputSpecification();
        $spec['validators'][] = array(
            'name' => 'Base\Validator\EntityUnique',
            'options' => array(
                'message' => 'Der name %value% ist bereits vergeben.',
                'entity' => 'User\Entity\User',
                'attribute' => 'username',  
            ),    
        );

        return $spec;
    }
}

when editin an existing user

<?php

namespace User\Form\Element;

use Zend\InputFilter\InputProviderInterface;
use User\Form\Element\Username;

class EditUsername extends Username implements InputProviderInterface
{
    protected $_userId;

    public function __construct($userId) {

        parent::__construct();
        $this->_userId = (integer)$userId;
    }

    public function getInputSpecification() {

        $spec = parent::getInputSpecification();
        $spec['validators'][] = array(
            'name' => 'Base\Validator\EntityUnique',
            'options' => array(
                'message' => 'Der name %value% ist bereits vergeben.',
                'entity' => 'User\Entity\User',
                'attribute' => 'username',
                'exclude' => array(
                    'attribute' => 'id',
                    'value' => $this->_userId,  
                ),
            ),    
        );

        return $spec;
    }
}

这篇关于如何在ZF2中创建表单输入/元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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