2つの問題があり、最初の段階はいくつかのステップでフォームを整理することでした-wizard-behavior(http://www.yiiframework.com/extension/wizard-behavior)はこれに対処するのに役立ちました。 少しやり直して、1つのアクションと1つのモデルを作成しました。 フィールド検証はスクリプト化されています。
必要なフィールドを含むレンダー部分ビューを介して、ajaxで作成された動的フィールドを追加します。
フォームはビューで作成されます:
$form=$this->beginWidget('CActiveForm', array( 'id'=>'create_order_step1', 'enableClientValidation'=>true, 'clientOptions'=>array( 'validateOnSubmit'=>true, 'validateOnType' => true, ),));
その中に、フィールドを追加するためのボタンを表示します:
echo CHtml::button(' ', array('class' => 'place-add btn')); <script> $(".place-add").click(function(){ var index = $(".new-place").size()+1; /// - . $.ajax({ success: function(html){ $("#add_place").append(html); // . }, type: 'get', url: '/index.php/site/field', // ajax action data: { index: index }, cache: false, dataType: 'html' }); }); </script>
アクション:
public function actionField($index = false) { $model = new CreateOrderForm(); $this->renderPartial('_add_place_fields', array( 'model' => $model, 'index' => $index, )); }
すでに+1であるブロック番号を取得します。
動的フィールド:
<table class="new-place" id="place_n<?php echo$index; ?>"> <tr> <td> <?php echo CHtml::activeTextField($model, "place_weight[$index]"); /// . echo CHtml::error($model, "place_weight[$index]"); // ?> </td> </tr> </table>
基本的に、アクションの検証を行う$ model-> validate(scenario)//スクリプトはステップに応じて変更されます。
検証が失敗した場合、モデル内のフィールドの数を見て、それをビューに渡します。 (検証エラー時に、動的に追加されたフィールドが消えないようにするため)
if(isset($model->attributes['place_weight'])){ $count = count($model->attributes['place_weight']); } $this->render('view', compact('model', 'count');
このため、これらのフィールドは次のように表示されます。
for($i =1; $i<$count; $i++){ $this->renderPartial('_add_place_fields', array( 'model' => $model, 'index' => $i, )); }
最も重要なこと-モデルと検証:
public function rules() { return array(array('place_weight', 'validatePlace', 'on'=>'step1'), ); } public function validatePlace($attribute,$params) // . { foreach($this->place_weight as $key_w => $weight){ if (empty($weight)) { $this->addError('place_weight['.$key_w.']', ' '); break; } } }
実際にはすべて。 yiiの初心者は、私のように、多くの時間を節約できると思います。