這些是我在SF2上的第一步。我想在包含其他實體的實體上設置多步表單。Symfony2將多步形式合併爲一個結果
我有一個表單類型(縮短)
class ApplicationFormType extends AbstractType
{
protected $_step = 1;
public function buildForm(FormBuilderInterface $builder, array $options)
{
if ($this->_step == 1) {
$builder
->add('patient', new Type\PersonType())
->add('insurance', 'entity', array(
'class' => 'Acme\MainBundle\Entity\Insurance',
));
} elseif ($this->_step == 2) {
$nurse = new Type\PersonType();
$nurse->requireBareData();
$builder
->add('nurse', $nurse)
->add('nurse_type', 'entity', array(
'class' => 'Acme\MainBundle\Entity\NurseType',
'expanded' => true,
'multiple' => false,
))
->add('nursing_support', 'checkbox', array(
'required' => false,
));
}
}
public function setStep($step)
{
$this->_step = $step;
}
我的控制器看起來像
public function assistAction() {
$request = $this->getRequest();
$step = $this->getSession()->get('assist_step', 1);
if ($request->getMethod() != 'POST') {
$step = 1;
$this->getSession()->set('assist_data', NULL);
}
$this->getSession()->set('assist_step', $step);
$application = new Application();
$type = new ApplicationFormType();
$type->setStep($step);
$form = $this->createForm($type, $application, array(
'validation_groups' => array($step == 1 ? 'FormStepOne' : 'FormStepTwo'),
));
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
if ($step == 1) {
$data = $form->getData();
$this->getSession()->set('assist_data', serialize($data));
$this->getSession()->set('assist_step', ++$step);
$type = new ApplicationFormType();
$type->setStep($step);
$form = $this->createForm($type, $application, array(
'validation_groups' => array('FormStepTwo'),
));
} else {
$step_1 = unserialize($this->getSession()->get('assist_data', ''));
$data = $form->getData();
=> $data->setPatient($step_1->getPatient());
=> $data->setInsurance($step_1->getInsurance());
$this->getSession()->set('assist_data', NULL);
$this->getSession()->set('assist_step', 1);
}
}
}
return $this->render('Acme:Default:onlineassist.html.twig', array(
'form' => $form->createView(),
'step' => $step,
));
}
我的問題是,如果我不得不「複製」第一種形式一步的性能seperately,像:
$data->setPatient($step_1->getPatient());
$data->setInsurance($step_1->getInsurance());
或I可以合併從會話中的序列化的數據和從第二形式數據STE P + 還是有一個完全不同的方法?
多步表單的最終目的是什麼?您希望在整個過程中保留提交的數據(如果有效),並且一旦客戶檢查數據,然後將其注入數據庫中,對嗎? – 2013-03-20 05:50:30
@ThomasPotaire:不完全。客戶端不檢查數據。正如你所看到的(在FormType中)第二步提供了另一個實體字段由用戶填充。 (並且會有第三步。)當用戶完成所有步驟時(順便說一句:第二個步驟很快就會選擇),包含所有相關實體的Application實體應該被保存到DB中。 – rabudde 2013-03-20 06:17:19