且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

处理 Zend Framework 2 表单中的依赖项

更新时间:2022-06-11 22:43:40

所以我做了一些小的改动:

So I got this to work with a few minor changes:

正如您所指出的,PropertyFieldSet 应该像这样调用父结构:

As you noted the PropertyFieldSet should call the parents construct like so:

parent::__construct('propertyfieldset'); 

ElementConfig 应该是这样的:

ElementConfig should be like so:

public function getFormElementConfig() {
    return array(
        'factories' => array(
            'PropertyFieldset' => function($sm) {
                $serviceLocator = $sm->getServiceLocator();
                $property_type = $serviceLocator->get('Ctmm\Model\PropertyType');
                $fieldset = new PropertyFieldset($property_type);
                return $fieldset;
            },
        )
    );
}

AddPropertyForm 应该是这样的:

And the AddPropertyForm should be like so:

namespace Ctmm\Form;
use Zend\Form\Form;

class AddPropertyForm extends Form {

    public function init() {

        parent::__construct('AddProperty');

        $this->setName('addProperty');
        $this->setAttribute('method', 'post');

        $this->add(array(
            'name' => 'addproperty',
            'type' => 'PropertyFieldset',
        ));
    }
}

我们使用 init() 代替 __construct.工厂实例化时显然会调用此函数:http://framework.zend.com/apidoc/2.1/classes/Zend.Form.Form.html#init

Instead of using __construct we use init(). This function is apparently called when instantiated by factory: http://framework.zend.com/apidoc/2.1/classes/Zend.Form.Form.html#init

关于构建选择,我会将 TableGateway 对象传递给 fieldSet 而不是模型.然后使用 fetchAll 函数,我们可以在表单中执行以下操作:

Regarding building the select, I would pass a TableGateway object to the fieldSet instead of a model. Then using a fetchAll function we could do the following in the form:

class PropertyFieldset extends Fieldset {

    public function __construct(PropertyTypeTable $propertyTypeTable) {
        parent::__construct('propertyfieldset');


        $propertyValOpts = array();
        foreach($propertyTypeTable->fetchAll() as $propertyRow) {
            array_push($propertyValOpts,$propertyRow->property_type);
        }

        $this->add(array(
            'name' => 'property_type',
            'type' => 'Zend\Form\Element\Select',
            'attributes' => array(
                'required' => true,
            ),
            'options' => array(
                'label' => 'Property Type',
                'value_options' => $propertyValOpts
            ),
        ));
    }
}

希望这有帮助:)