ZF2 - 未找到表单中的元素

时间:2013-10-23 16:24:58

标签: php zend-framework2

我不明白。这是我的字段集:

<?php
namespace example\Form;

use example\Entity\User;
use example\Entity\Strategy\PasswordStrategy;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;

class UserFieldset extends Fieldset implements InputFilterProviderInterface
{
    public function __construct(ObjectManager $objectManager)
    {
        parent::__construct('user');

        $this->add(array(
            'name' => 'id',
            'type' => 'Zend\Form\Element\Hidden',
        ));

    }

    public function getInputFilterSpecification()
    {
        return array();
    }
}

这是我的表格:

<?php
namespace example\Form;

use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Form;
use example\Form\UserFieldset;

class UserForm extends Form
{
    public function __construct(ObjectManager $objectManager)
    {
        parent::__construct('user-form');

        $userFieldset = new UserFieldset($objectManager);
        $userFieldset->setUseAsBaseFieldset(true);

        $this->add($userFieldset);

        $this->add(array(
            'name' => 'submit',
            'type'  => 'Zend\Form\Element\Submit',
            'attributes' => array(
                'value' => 'Go',
                'id' => 'submitbutton',
            ),
        ));
    }
}

我的行动:

public function userAction()
{
    $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
    $userForm = new UserForm($objectManager);
    return array(
        'form' => $userForm
    );
}

我的观点:

<?php
$form = $this->form;
$form->setAttribute('action', $this->url('user'));
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formRow($form->get('id'));
echo $this->formRow($form->get('submit'));
echo $this->form()->closeTag();

我的错误:

在表单

中找不到[id]名称的元素

为什么呢?只是提交字段呈现正常,但只要我添加id字段,我就会收到错误...

2 个答案:

答案 0 :(得分:1)

尝试

echo $this->formRow($form->get('user')->get('id'));

您需要通过字段集获取此元素。

答案 1 :(得分:1)

您可以使用 FormCollection()

进行渲染
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('user'));
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formCollection($form->get('user'));
echo $this->form()->closeTag();

或者像这样

<?php
$form = $this->form;
$form->setAttribute('action', $this->url('user'));
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formRow($form->get('user')->get("id"));
echo $this->formRow($form->get('user')->get("submit"));
echo $this->form()->closeTag();