2015-04-07 41 views
0

我想使用幫助函數填充zend表單中的選擇框。如何在zf2中使用幫助函數

以下是助手和表單代碼。 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; 
} 

} 

我不知道如何在這裏調用輔助函數。請幫助我對ZF2相對較新。

我粘貼的代碼實際上是樣本getMyList函數是假設填充冗長的數組,我不想把這個冗長的數組放在窗體中,因爲我將在幾個更多的地方重複使用數組。

回答

0

明白了。 我可以通過控制器的servicelocator。

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