我正在尝试使用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);
  }
 }

这种方法有意义吗?还是我脱离了基础,并且在Yii/PHP中有更好,更优化的方法来做到这一点?

谢谢!

最佳答案

有两种方法可以解决此问题。我看到您发布在Yii论坛上,所以我假设您也在附近搜索过,但如果您没有这样做:

  • http://www.yiiframework.com/forum/index.php?/topic/6203-stateful-forms-and-wizards-howto/
  • http://www.yiiframework.com/forum/index.php?/topic/8413-wizard-forms/

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

    像您这样的隐藏的“步骤”字段可以起到与检查SubmitButton名称相同的作用。我也许可以将“步骤”保存到表单状态中,而不是添加一个隐藏字段,但是两者都可以。

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

    这是我基本上对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));
    } ?>
    

    表单看起来像这样:

    表格1:
    <?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(); ?>
    

    表格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(); ?>
    

    希望对您有所帮助!

    10-08 07:58
    查看更多