Yii多页面表单向导最佳实践

Sti*_*ofu 23 php yii yii1.x

我正在尝试使用Yii构建一个多页面的表单,但我对PHP和Yii很新,我想知道编写多页面表单的最佳实践是什么.到目前为止,我打算做的是添加一个名为"step"的隐藏字段,其中包含用户在表单中的当前步骤(表单分为3个步骤/页).所以考虑到这一点,这就是我打算如何处理用户点击Controller中的上一个/下一个按钮:

public function actionCreate()
 {
  $userModel = new User;

  $data['activityModel'] = $activityModel; 
  $data['userModel'] = $userModel; 

  if (!empty($_POST['step']))
  {
   switch $_POST['step']:
    case '1':
     $this->render('create_step1', $data);
     break;

    case '2':
     $this->render('create_step2', $data);
     break;

  }else
  {
   $this->render('create_step1', $data);
  }
 }
Run Code Online (Sandbox Code Playgroud)

这种方法有意义吗?或者我离开基地,在Yii/PHP中有更好,更优化的方法吗?

谢谢!

tha*_*smt 35

有几种方法可以解决这个问题.我看到你发布在Yii论坛上,所以我假设你也在那里搜索过,但万一你还没有:

我所做的是(仅用于简单的两步ActiveRecord表单)采取单个操作并将其分为基于按钮名称的条件块,Yii POST在表单上提交(注意:不适用于ajax提交).然后,根据点击的按钮,我呈现正确的表单并在我的模型上设置正确的场景以进行验证.

像你一样隐藏的"步骤"字段可以起到与检查submitButton名称相同的目的.我可能会将"步骤"保存到表单状态,而不是添加一个隐藏字段,但要么就好了.

有些人使用有状态activeForm属性从向导中的单个步骤保存数据,或者您可以使用会话,甚至可以保存到临时数据库表.在我下面完全未经测试的示例中,我使用的是有状态表单功能.

这是我基本上为ActiveRecord表单做的一个例子.这包含在"actionCreate"中:

<?php if (isset($_POST['cancel'])) {
  $this->redirect(array('home'));
} elseif (isset($_POST['step2'])) {
  $this->setPageState('step1',$_POST['Model']); // save step1 into form state
  $model=new Model('step1');
  $model->attributes = $_POST['Model'];
  if($model->validate())
    $this->render('form2',array('model'=>$model));
  else {
    $this->render('form1',array('model'=>$model));
  }
} elseif (isset($_POST['finish'])) {
  $model=new Model('finish');
  $model->attributes = $this->getPageState('step1',array()); //get the info from step 1
  $model->attributes = $_POST['Model']; // then the info from step2
  if ($model->save())
    $this->redirect(array('home'));
  else {
    $this->render('form2',array('model'=>$model));
} else { // this is the default, first time (step1)
  $model=new Model('new');
  $this->render('form1',array('model'=>$model));
} ?>
Run Code Online (Sandbox Code Playgroud)

表单看起来像这样:

Form1中:

<?php $form=$this->beginWidget('CActiveForm', array(
    'enableAjaxValidation'=>false,
    'id'=>'model-form',
    'stateful'=>true,
));
<!-- form1 fields go here -->
echo CHtml::submitButton("Cancel",array('name'=>'cancel');
echo CHtml::submitButton("On to Step 2 >",array('name'=>'step2');
$this->endWidget(); ?>
Run Code Online (Sandbox Code Playgroud)

表格2:

<?php $form=$this->beginWidget('CActiveForm', array(
    'enableAjaxValidation'=>false,
    'id'=>'model-form',
    'stateful'=>true,
));
<!-- form2 fields go here -->
echo CHtml::submitButton("Back to Step 1",array('name'=>'step1');
echo CHtml::submitButton("Finish",array('name'=>'finish');
$this->endWidget(); ?>
Run Code Online (Sandbox Code Playgroud)

我希望这对你有所帮助!