我将使用不同的方法在 Symfony 中实现多部分表单。希望以下 shell 足以让您入门。
第 1 步:在表单中添加阶段小部件
public function configure()
{
$this->setWidget('stage', new sfWidgetFormInputHidden(array('default' => 1));
$this->setValidator('stage', new sfValidatorFormInteger(array('min' => 1, 'max' => $maxStages, 'required' => true));
}
第 2 步:在表单中添加有关阶段的一些信息
protected $stages = array(
1 => array('stage1field1', 'stage1field2',
2 => array('stage2field1', ... //etc for as many stages you have
);
第 3 步:在表单中添加 configure as stage 方法
public function configureAsStage($currentStage)
{
foreach($this->stages as $stage => $field)
{
if ($currentStage > $stage)
{
$this->setWidget($stage, new sfWidgetFormInputHidden()); //so these values carry through
}
if ($stage > $currentStage)
{
unset($this[$stage]); //we don't want this stage here yet
}
}
}
第 4 步:覆盖 doBind
你可能需要bind()
直接覆盖,我忘了。
public function doBind(array $taintedValues)
{
$cleanStage = $this->getValidator('stage')->clean($taintedValues['stage']);
$this->configureAsStage($cleanStage);
parent::doBind($taintedValues);
}
第五步:在表单中添加一些辅助方法
public function advanceStage()
{
if ($this->isValid())
{
$this->values['stage'] += 1;
$this->taintedValues['stage'] += 1;
$this->resetFormFields();
}
}
public function isLastStage()
{
return $this->getValue('stage') == count($this->stages);
}
第 6 步:在您的操作中根据需要调用 configureAsStage/advanceStage
public function executeNew(sfWebRequest $request)
{
$form = new MultiStageForm($record);
$form->configureAsStep(1);
}
public function executeCreate(sfWebRequest $request)
{
$record = new Record();
$form = new MultiStageForm($record);
$form->bind($request[$form->getName()]);
if ($form->isValid())
{
if ($form->isLastStage())
{
$form->save();
//redirect or whatever you do here
}
$form->advanceStage();
}
//render form
}
我完全是在飞行中编造的。我认为它应该可以工作,但我还没有测试过,所以可能会有一些错误!