3

根据 Zend Framework 2 手册(此处),我制作了这样的表格:

class ParentForm extends Form
{
    public function init()
    {   
        $this->setName('parent_form')
             ->setAttribute('method', 'post')
             ->setHydrator(new ClassMethods(true))
             ->setInputFilter(new InputFilter());

        $this->add(array(
            'type' => 'Application\Form\Fieldset\Parent',
            'name' => 'parent',
            'options' => array(
                'label'                => 'Parent',
                'use_as_base_fieldset' => true
            )
        ));

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

        $this->add(array(
            'name' => 'submit',
            'attributes' => array(
                'type' => 'submit',
                'value' => 'Send'
            )
        ));
    }
}

和“父”字段集:

class ParentFieldset extends Fieldset
{    
    protected $count = 2;    

    public function init()
    {   
        $this->setName('parent_fieldset')
             ->setHydrator(new ClassMethodsHydrator(false))
             ->setObject(new Model\Parent());

        $this->add(array('type' => 'Element\MyField'));            

        $this->add(array(
            'type' => 'collection',
            'name' => 'children',
            'options' => array(
                'label'                  => 'Children',
                'count'                  => $this->count,
                'should_create_template' => true,
                'allow_add'              => true,
                'target_element'         => array(
                    'type'    => 'Application\Form\Fieldset\Child',
                    'name'    => 'child',
                    'options' => array(
                        'label' => child',
                    ),
                ),
            )
        ));
    }

    public function setCount($count)
    {
        $this->count = max($count, 2);
    }
}

这非常适合使用从我的表单中获得的数据来补充我的 Parent 对象。返回对象的 var_dump 如下所示:

object(Parent)
public myField  => foo
public children =>
 array => 
  0 => object(Child)
    public field1 => value1
    public field2 => value2
    ....
  1 => object(Child)
    .....
  2 => object(Child)
    .....

但是如果从数据库中水合(用于编辑目的),我无法弄清楚如何用上述对象填充这个多维表单。我怎样才能做到这一点?

注意:表单中的 count 属性设置为与对象中相同的子项数。

4

0 回答 0