📜 ⬆️ ⬇️

Validation of dynamically added fields in Yii

It all started with a new job, which had to give up on Zend and go to Yii. When creating a personal account for the site, it was necessary to dynamically add fields in the form. After picking on the Internet, such a decision came. Go:

There were 2 problems. The first is to organize the form in a few steps - wizard-behavior helped to cope with this (http://www.yiiframework.com/extension/wizard-behavior). A little remake, made for one action and one model. Validation of fields is based on scripts.
Adding dynamic fields made via ajax through a render-partial view that contained the required fields.

The form is created in view:
$form=$this->beginWidget('CActiveForm', array( 'id'=>'create_order_step1', 'enableClientValidation'=>true, 'clientOptions'=>array( 'validateOnSubmit'=>true, 'validateOnType' => true, ),)); 

In it, we also display a button for adding fields:
 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> 

Action:
 public function actionField($index = false) { $model = new CreateOrderForm(); $this->renderPartial('_add_place_fields', array( 'model' => $model, 'index' => $index, )); } 

We get the block number, which is already +1.

Dynamic fields:
 <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> 

Basically the action validation is done just $ model-> validate (scenario) // the scenario changed depending on the step.
If validation did not pass then we look at the number of fields in the model and give in the view. (So ​​that during the validation error the dynamically added fields do not disappear)
 if(isset($model->attributes['place_weight'])){ $count = count($model->attributes['place_weight']); } $this->render('view', compact('model', 'count'); 

In view for this, we display these fields as follows:
 for($i =1; $i<$count; $i++){ $this->renderPartial('_add_place_fields', array( 'model' => $model, 'index' => $i, )); } 

')
And most importantly - Model and validation:

 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; } } } 

Actually everything. I think a beginner in yii, like me it will reduce a lot of time.

Source: https://habr.com/ru/post/181642/


All Articles