ZF2 Form和Doctrine 2修改value_options [英] ZF2 Form and Doctrine 2 modify the value_options

查看:150
本文介绍了ZF2 Form和Doctrine 2修改value_options的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Zend Framework 2项目中使用了Doctrine 2。我现在已经创建了一个表单,并从数据库中创建了一个带有值的下拉列表。我现在的问题是,我想要更改使用哪些值,而不是从我的存储库返回的值。好的,这里有一些代码可以更好地理解:

  $ this-> add(
array(
'type'=>'DoctrineModule\Form\Element\ObjectSelect',
'name'=>'county',

'options'=>数组
'object_manager'=> $ this-> getObjectManager(),
'label'=>'县',
'target_class'=>'Advert \Entity\ Geolocation',
'property'=>'county',
'is_method'=> true,
'empty_option'=>'--- select county ---'
'value_options'=> function($ targetEntity){
$ values = array($ targetEntity-> getCounty()=> $ targetEntity - > getCounty());
返回$ values;
},

'find_method'=>数组(
'name'=>'getCounties',
),
),
'allow_empty'=> true,
'required'=> false,
'attributes'=> array(
'id'=>'county',
'multiple'=> false,


);

我想为我的Select设置值为县名,而不是ID。我以为我需要一个需要一个数组的'value_options'。我尝试像上面那样,但是得到



错误消息:参数1传递给Zend\Form\Element\Select :: setValueOptions()必须是类型数组,给定的对象



这是可能的吗?

解决方案

我建议修改你的代码,虽然在检查 ObjectSelect 代码后,我很惊讶(据我所知)实际上没有延长班级的可能性。这是因为该值为始终从id生成



我使用工厂创建所有表单元素(不含 ObjectSelect ),特别是复杂的,需要不同的列表。



替代解决方案



首先在Repository中创建一个返回正确数组的新方法。这将允许您重复使用相同的方法,如果您需要它在其他任何地方(不只是为了表单!)。

  class FooRepository extends存储库
{
public function getCounties()
{
//常规方法不变,返回一个集合
//县
}

public function getCountiesAsArrayKeyedByCountyName()
{
$ counties = array();
foreach($ this-> getCounties()as $ county){
$ county [$ county-> getName()] = $ county-> getName();
}
return $县
}
}

接下来创建一个自定义选择工厂,将设置值

 命名空间MyModule\Form\Element; 

使用Zend\Form\Element\Select;
使用Zend\ServiceManager\ServiceLocatorInterface;
使用Zend\ServiceManager\FactoryInterface;

class CountiesByNameSelectFactory实现FactoryInterface
{
public function createService(ServiceLocatorInterface $ formElementManager)
{
$ element = new Select;
$ element-> setValueOptions($ this-> loadValueOptions($ formElementManager));

//设置其他选择选项etc
$ element-> setName('foo')
- > setOptions(array('foo'=>'bar' ));

return $ element;
}

protected function loadValueOptions(ServiceLocatorInterface $ formElementManager)
{
$ serviceManager = $ formElementManager-> getServiceLocator();
$ repository = $ serviceManager-> get('DoctrineObjectManager') - > getRepository('Foo / Entity / Bar');

return $ repository-> getCountiesAsArrayKeyedByCountyName();
}

}

使用服务注册新元素经理通过在 Module.php module.config.php 中添加新条目。

  // Module.php 
public function getFormElementConfig()
{
return array(
'factoryories =>数组(
'MyModule\Form\Element\CountiesByNameSelect'
=>'MyModule\Form\Element\CountiesByNameSelectFactory',
),
);
}

最后更改表单和删除您当前的选择元素并添加新的(使用您在服务管理器中注册的名称作为类型键)

  $ this-> ; add(array(
'name'=>'county',
'type'=>'MyModule\Form\Element\CountiesByNameSelect',
));

这可能看起来像是更多的代码(因为它是),但是你会受益于它更清楚的分离关注点,您现在可以在多个表单上重用该元素,并且只需要在一个地方进行配置。


I am using Doctrine 2 in my Zend Framework 2 Project. I have now created a Form and create one of my Dropdowns with Values from the Database. My Problem now is that I want to change which values are used and not the one which I get back from my repository. Okay, here some Code for a better understanding:

$this->add(
            array(
                    'type' => 'DoctrineModule\Form\Element\ObjectSelect',
                    'name' => 'county',

                    'options' => array(
                            'object_manager' => $this->getObjectManager(),
                            'label' => 'County',
                            'target_class'   => 'Advert\Entity\Geolocation',
                            'property'       => 'county',
                            'is_method' => true,
                            'empty_option' => '--- select county ---',
                            'value_options'=> function($targetEntity) {
                                $values = array($targetEntity->getCounty() => $targetEntity->getCounty());
                                return $values;
                            },

                            'find_method'        => array(
                                    'name'   => 'getCounties',
                            ),
                    ),
                    'allow_empty'  => true,
                    'required'     => false,
                    'attributes' => array(
                            'id' => 'county',
                            'multiple' => false,
                    )
            )
    ); 

I want to set the value for my Select to be the County Name and not the ID. I thought that I would need the 'value_options' which needs an array. I tried it like above, but get the

Error Message: Argument 1 passed to Zend\Form\Element\Select::setValueOptions() must be of the type array, object given

Is this possible at all?

解决方案

I was going to suggest modifying your code, although after checking the ObjectSelect code i'm surprised that (as far as I can tell) this isn't actually possible without extending the class. This is because the value is always generated from the id.

I create all form elements using factories (without the ObjectSelect), especially complex ones that require varied lists.

Alternative solution

First create a new method in the Repository that returns the correct array. This will allow you to reuse that same method should you need it anywhere else (not just for forms!).

class FooRepository extends Repository
{
    public function getCounties()
    {
        // normal method unchanged, returns a collection
        // of counties
    }

    public function getCountiesAsArrayKeyedByCountyName()
    {
        $counties = array();
        foreach($this->getCounties() as $county) {
            $counties[$county->getName()] = $county->getName();
        }
        return $counties;
    }
}

Next create a custom select factory that will set the value options for you.

namespace MyModule\Form\Element;

use Zend\Form\Element\Select;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;

class CountiesByNameSelectFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $formElementManager)
    {
        $element = new Select;
        $element->setValueOptions($this->loadValueOptions($formElementManager));

        // set other select options etc
        $element->setName('foo')
                ->setOptions(array('foo' => 'bar'));

        return $element;
    }

    protected function loadValueOptions(ServiceLocatorInterface $formElementManager)
    {
        $serviceManager = $formElementManager->getServiceLocator();
        $repository = $serviceManager->get('DoctrineObjectManager')->getRepository('Foo/Entity/Bar');

        return $repository->getCountiesAsArrayKeyedByCountyName();
    }

}

Register the new element with the service manager by adding a new entry in Module.php or module.config.php.

// Module.php
public function getFormElementConfig()
{
    return array(
        'factories' => array(
            'MyModule\Form\Element\CountiesByNameSelect'
                => 'MyModule\Form\Element\CountiesByNameSelectFactory',
        ),
    );
}

Lastly change the form and remove your current select element and add the new one (use the name that you registered with the service manager as the type key)

$this->add(array(
    'name' => 'counties',
    'type' => 'MyModule\Form\Element\CountiesByNameSelect',
));

It might seem like a lot more code (because it is) however you will benefit from it being a much clearer separation of concerns and you can now reuse the element on multiple forms and only need to configure it in one place.

这篇关于ZF2 Form和Doctrine 2修改value_options的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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