zf2表单绑定对象问题

Raj*_*Raj 2 forms binding zend-framework2

我有一个zf2问题,形式绑定对象程序,简而言之我试图通过表单验证通过表单对象自动化数据交换到我的实体,为此我实现了两个接口InputFilterAwareInterfaceArraySerializableInterface,早期的接口是表单对象获取输入过滤器,后面的接口用于表单和我的实体的数据交换.下面是我控制器中放置的代码的简短片段.

//Controller code
$companyForm = new \Manage\Forms\CompanyForm();
$companyEntity = $this->getServiceLocator()->get('Manage/CompanyEntity');
$postData = $this->getRequest()->getPost()->toArray();
$companyEntity->exchangeArray($postData);
$companyForm->bind($companyEntity);
if($companyForm->isValid(){
    ....
}
Run Code Online (Sandbox Code Playgroud)

这应该在我的实体对象中自动调用exchangeArray()方法并且它正确地执行问题数据是空的,并且数据数组包含具有inputfilter设置的键,所有其他数据键都丢失.

如果需要,我可以添加更多代码片段.

谢谢Raj

Jur*_*man 5

将实体与表格结合通常使用保湿剂完成.水化器将数据数组转换为值对象,反之亦然.因此,您需要配置表单以使适合您实体的正确保湿器.

如果你有,例如,各种属性(比如,barbaz)为您的实体Foo和配置getBar(),setBar(),getBaz()setBaz()方法,你可以使用ClassMethods水化:

use Zend\Form\Form;
use Zend\StdLib\Hydrator\ClassMethods;

class Foo extends Form
{
    public function __construct()
    {
        parent::__construct();

        $this->setHydrator(new ClassMethods);

       // More here for the elements now
    }
}
Run Code Online (Sandbox Code Playgroud)

而你的实体:

class Foo
{
    public function getBar() {...}
    public function setBar() {...}

    public function getBaz() {...}
    public function setBaz() {...}
}
Run Code Online (Sandbox Code Playgroud)

然后你的控制器看起来像这样:

public function createAction()
{
    $entity = new My\Entity\Foo;
    $form   = new My\Form\Foo;
    $form->bind($entity);

    if ($this->getRequest()->isPost()) {
        $data = $this->getRequiest()->getPost();
        $form->setData($data);

        if ($form->isValid()) {
            // $entity is now populated with data
            // persist $entity here
        }
    }

    // create view model here
}
Run Code Online (Sandbox Code Playgroud)

如果您的表单中包含"bar"和"baz"元素并提供正确的输入过滤器以获取"bar"和"baz"表单数据并对其进行过滤,则此方法将起作用.