我正在努力尝试使用单一表单来编辑多个模型。
我有一个名为Teams的数据库表和一个与该表关联的doctrine实体。我创建了一个表单如下:
我的团队字段:
class TeamFieldset extends AbstractFieldset implements InputFilterProviderInterface
{
public function init()
{
$this->setName('Team')
->setHydrator(new DoctrineHydrator($this->getObjectManager(),'Application\Model\Entities\Team'))
->setObject(new Team())
->setLabel('Team');
$this->add(array(
'type' => 'Hidden',
'name' => 'id',
));
$this->add(array(
'name' => 'name',
'options' => array(
'label' => 'Team name',
),
));
// …. more fields go here
}
/**
* Implement InputFilterProviderInterface
*/
public function getInputFilterSpecification()
{
// …. input filter implementation goes here.
}
}
我的团队成员:
class TeamForm extends AbstractAdminForm
{
public function init()
{
parent::init();
$this->setName('team-form')
->add(array(
'type' => 'TeamFieldset',
'name' => 'Team',
'options' => array(
'use_as_base_fieldset' => true,
),
)
);
$this->add(array(
'name' => 'submit',
'options' => array(
'label' => 'Save Team',
),
'attributes' => array(
'class' => 'btn-primary',
'type' => 'submit',
),
));
}
}
在我的控制器中:
public function editTeamAction()
{
$team = $this->getEntityManager()->find('Application\Model\Entities\Team',$this->params()->fromRoute('team_id'));
$formManager = $this->serviceLocator->get('FormElementManager');
$form = $formManager->get('Application\Form\Team\TeamForm');
$form->setAttribute('action',$_SERVER['REQUEST_URI']);
$form->bind($team);
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getEntityManager()->persist($team);
$this->getEntityManager()->flush();
$this->redirect()->toRoute('admin/leagues/league/team',array('league_id' => $team->getLeague()->getId(),'team_id' => $team->getId()));
}
}
return array(
'team' => $team,
'form' => $form
);
}
到目前为止,这一切都很好并且效果很好。
现在,我还有一个遗留数据库,其中包含另一个Teams表。我希望用户能够通过相同的表单进行编辑。
我没有对遗留数据库使用doctrine,但这是无关紧要的,我可以很快将相应的记录拉出到一个数组中,然后为它创建一个带有数组保持器的字段集。
但是,您在窗体上调用绑定函数,而不是在字段集上调用。那么如何使用表单上的单个绑定操作将数据绑定到每个字段集?
如果在fielset上有绑定操作,那就不是问题,我可以从表单中提取每个字段集并与适当的对象绑定。
非常感谢任何指针。
:WQ
答案 0 :(得分:1)
您可以使用Zend\Stdlib\Hydrator\Aggregate\AggregateHydrator
当您想要从实现多个界面的复杂对象中水合或提取数据时,通常需要使用聚合水化器,因此在后续步骤中需要多个水化器来处理它。