【发布时间】:2014-05-14 16:14:17
【问题描述】:
我正在努力研究如何使用一个表单来编辑多个模型。
我有一个名为 Teams 的数据库表和一个与该表关联的学说实体。我创建了一个如下表格:
我的团队字段集:
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 表。我希望用户能够通过相同的表单进行编辑。
我没有对遗留数据库使用原则,但这无关紧要,我可以很快将适当的记录拉出到一个数组中,然后为它创建一个带有数组水合器的字段集。
但是,您在表单上调用绑定函数,而不是在字段集上。那么如何使用表单上的单个绑定操作将数据绑定到每个字段集呢?
如果在字段集上有绑定操作,这不会是问题,我可以从表单中拉出每个字段集并与适当的对象绑定。
任何指针将不胜感激。
:wq
【问题讨论】:
标签: php doctrine-orm zend-framework2 zend-form