我正在尝试通过ZF2 FormElementManager构建一个表单,并在网上跟踪了一些示例,包括Zend自己的说明:
http://framework.zend.com/manual/2.1/en/modules/zend.form.advanced-use-of-forms.html
Module.php
use Zend\ModuleManager\Feature\FormElementProviderInterface;
use Application\Form\PlayerFieldset;
class Module implements FormElementProviderInterface
{
public function getFormElementConfig()
{
return array(
'factories' => array(
'PlayerFieldset' => function ($sm) {
return new Form\PlayerFieldset();
},
),
);
}
}
IndexController.php
class IndexController extends AbstractActionController
{
public function indexAction()
{
$formManager = $sm->get('FormElementManager');
$form = $formManager->get('Application\Form\PlayerForm');
$formViewObj = new ViewModel(array('form' => $form));
$formViewObj->setTemplate('application/widgets/form.phtml');
return $formViewObj;
}
}
PlayerForm.php
use Zend\Form\Form;
class PlayerForm extends Form
{
public function init()
{
$this->add(array(
'name' => 'playerdetails',
'type' => 'PlayerFieldset',
));
}
}
PlayerFieldset.php
class PlayerFieldset extends Fieldset implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
public function init()
{
parent::__construct('Player');
$this->setHydrator(new ClassMethodsHydrator(false))
->setObject(new Player());
$sm = $this->getFormFactory()->getFormElementManager()->getServiceLocator();
$msi = $sm->get('MyServiceInterface');
$elements = $msi->request('FieldManager','getFieldsByEntity','Player');
// Add fields to fieldset
foreach ($elements as $element) {
$this->add($element);
}
}
}
在PlayerFieldset.php
的末尾,这些元素已添加到$this
(我可以通过调用$this->getElements();
并打印出结果来看到这一点。
然而,回到IndexController.php
$form
对象没有附加我的元素。
任何人都可以帮我解释原因吗?
答案 0 :(得分:0)
表单不会有 fieldset
的元素所以而不是表单元素:
$form->getElements();
您需要首先获取playerdetails
字段集,然后返回它的元素。
$form->get('playerdetails')->getElements();