如何在zf2中使用表单中的helper函数


how to use helper function in form in zf2

我想使用helper函数填充zend表单中的选择框。

以下是帮助程序和表单代码。myhelper.php

namespace myspace'View'Helper;
use Zend'View'Helper'AbstractHelper,
Zend'ServiceManager'ServiceLocatorInterface as ServiceLocator;
use Zend'Db'ResultSet'ResultSet;
class MyHelper extends AbstractHelper {
protected $serviceLocator;
protected $dbAdapter;
protected $resultData;
public function __construct(ServiceLocator $serviceLocator) {
    $this->serviceLocator = $serviceLocator;
}
public function getMyList() {
    return $states = array(
        'a' => 'a',
        'b' => 'b',
        'c' => 'c', );
}
public function getServiceLocator() {
    return $this->serviceLocator;
} 
}

我的表单代码Myform.php

namespace myspace'Form;
use Zend'Form'Form;
use Zend'Db'Adapter'AdapterInterface;
use Zend'Form'Element;
use masterinfo'View'Helper'MasterHelper;
use Zend'ServiceManager'ServiceLocatorAwareInterface;
use Zend'ServiceManager'ServiceLocatorInterface;
class UserForm extends Form implements ServiceLocatorAwareInterface {
protected $dbAdapter;
protected $serviceLocator;
public function __construct($args) {
    parent::__construct('user');
    $dbAdapter = $args['dbAdapter']; 
    $this->setDbAdapter($dbAdapter);
    $this->setAttribute('method', 'post');
    $this->setAttribute('class', 'form-horizontal');
    $this->setAttribute('role', 'form');
    $this->setAttribute('enctype', 'multipart/form-data');
    $this->add(array(
        'name' => 'testselect',
        'type' => 'Zend'Form'Element'Select',
        'attributes' => array(
            'class' => 'single-select',
            'id' => 'testselect',
            'required' => 'required',
        ),
        'options' => array(
            'value_options' => /***here I need to call helper function getMyList()****/,
            'empty_option' => 'Select Status'
        ),
    ));
}
function setDbAdapter(AdapterInterface $dbAdapter) {
    $this->dbAdapter = $dbAdapter;
}
function getDbAdapter() {
    return $this->dbAdapter;
}
public function getServiceLocator() {
    return $this->serviceLocator;
}
public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
    $this->serviceLocator = $serviceLocator;
}
}

我不知道如何在这里调用helper函数。请帮忙,我对ZF2还比较陌生。

我粘贴的代码是一个示例,实际上getMyList函数是用来填充长数组的,我不想把这个长数组放在表单中,因为我会在更多的地方重用这个数组。

自己得到的。我可以从控制器传递服务定位器。

$form = new 'myspace'Form'UserForm(array('dbAdapter' => $dbAdapter,'sm'=>$this->getServiceLocator()));

然后以的形式

....
....
$this->add(array(
    'name' => 'testselect',
    'type' => 'Zend'Form'Element'Select',
    'attributes' => array(
        'class' => 'single-select',
        'id' => 'testselect',
        'required' => 'required',
    ),
    'options' => array(
        'value_options' => $this->getMyArray($args['sm']),
        'empty_option' => 'Select Status'
    ),
));
....
....
function getMyArray($serviceLocator) {
    $master = new MyHelper($serviceLocator);
    return $master->getMyList();
}