php - YII2 : Add Dynamic form fields and their validations -


i adding dynamic form fields onchange of dropdown. both types of fields coming different models , go database in different tables. have defined validation rules in models.

but validation not working properly. code follows:

model :

<?php  namespace common\models;  use yii;  /**  * model class table "{{%membership_features}}".  *  * @property integer $id  * @property string $title  * @property string $type  * @property integer $is_new  * @property integer $status  * @property integer $is_deleted  * @property string $created_date  * @property string $modified_date  *  * @property membershipfeaturesvalue[] $membershipfeaturesvalues  */ class membershipfeatures extends \yii\db\activerecord {     /**      * @inheritdoc      */      public $value=[];     public static function tablename()     {         return '{{%membership_features}}';     }      /**      * @inheritdoc      */     public function rules()     {         return [             [['title', 'type', 'value','is_new', 'status'], 'required'],             ['value', 'each', 'rule' => ['integer']],             ['value', 'each', 'rule' => ['required']],             [['is_new', 'status', 'value','is_deleted'], 'integer'],             [['created_date', 'modified_date'], 'safe'],             [['title', 'type'], 'string', 'max' => 255]         ];     }      /**      * @inheritdoc      */     public function attributelabels()     {         return [             'id' => yii::t('app', 'id'),             'title' => yii::t('app', 'title'),             'type' => yii::t('app', 'is boolean or value'),             'is_new' => yii::t('app', 'is new'),             'status' => yii::t('app', 'status'),             'is_deleted' => yii::t('app', 'is deleted'),             'created_date' => yii::t('app', 'created date'),             'modified_date' => yii::t('app', 'modified date'),         ];     }      /**      * @return \yii\db\activequery      */     public function getmembershipfeaturesvalues()     {         return $this->hasmany(membershipfeaturesvalue::classname(), ['feature_id' => 'id']);     } } 

controller :

<?php  namespace backend\controllers;  use yii; use common\models\membershipfeatures; use backend\models\membershipfeaturessearch; use yii\web\controller; use yii\web\notfoundhttpexception; use yii\filters\verbfilter; use yii\web\response; use common\models\membershipfeaturesvalue; use common\components\helper; /**  * membershipfeaturescontroller implements crud actions membershipfeatures model.  */ class membershipfeaturescontroller extends controller {     public function behaviors()     {         return [             'verbs' => [                 'class' => verbfilter::classname(),                 'actions' => [                     'delete' => ['post'],                 ],             ],         ];     }      /**      * lists membershipfeatures models.      * @return mixed      */     public function actionindex()     {         $searchmodel = new membershipfeaturessearch();         $dataprovider = $searchmodel->search(yii::$app->request->queryparams);          return $this->render('index', [             'searchmodel' => $searchmodel,             'dataprovider' => $dataprovider,         ]);     }      /**      * displays single membershipfeatures model.      * @param integer $id      * @return mixed      */     public function actionview($id)     {         return $this->render('view', [             'model' => $this->findmodel($id),         ]);     }      /**      * creates new membershipfeatures model.      * if creation successful, browser redirected 'view' page.      * @return mixed      */     public function actioncreate()     {         $model = new membershipfeatures();         $membershipplan = \common\models\membershipplan::allplans();          if(isset($_get['type'])){             $model->type =$_get['type'];         }         if (yii::$app->request->isajax  && $model->load(yii::$app->request->post())) {              yii::$app->response->format = response::format_json;             return \yii\widgets\activeform::validate($model);         }          if ($model->load(yii::$app->request->post()) ) {              if( $model->save()){                    foreach ($membershipplan $key=>$value) {                     $feature = new membershipfeaturesvalue();                     $feature->feature_id = $model->id;                     $feature->plan_id = $key;                     $feature->value =$model->value[$key];                     $feature->save();                 }             }                return $this->redirect(['index']);         }              return $this->render('create', [                 'model' => $model,                 'membershipplan'=>$membershipplan,              ]);      }      /**      * updates existing membershipfeatures model.      * if update successful, browser redirected 'view' page.      * @param integer $id      * @return mixed      */     public function actionupdate($id)     {             $membershipplan = \common\models\membershipplan::allplans();             $model = $this->findmodel($id);          $selected = membershipfeaturesvalue::find()->where(['feature_id'=>$model->id])->all();         foreach ($selected $key => $value) {                 $model->value[$value->plan_id]=$value->value;         }              if(isset($_get['type'])){             $model->type =$_get['type'];         }         if(yii::$app->request->isajax  && $model->load(yii::$app->request->post())) {              yii::$app->response->format = response::format_json;             return \yii\widgets\activeform::validate($model);         }          if ($model->load(yii::$app->request->post()) ) {              if( $model->save()){                    foreach ($membershipplan $key=>$value) {                     $feature = membershipfeaturesvalue::find()->where(['feature_id'=>$model->id,'plan_id'=>$key])->one();                     $feature->value =$model->value[$key];                     $feature->save();                 }             }                return $this->redirect(['index']);         }            return $this->render('update', [                 'model' => $model,                 'membershipplan'=>$membershipplan,              ]);      }      /**      * deletes existing membershipfeatures model.      * if deletion successful, browser redirected 'index' page.      * @param integer $id      * @return mixed      */     public function actiondelete($id)     {         helper::partialdelete('membershipfeatures',$id);          return $this->redirect(['index']);     }      /**      * finds membershipfeatures model based on primary key value.      * if model not found, 404 http exception thrown.      * @param integer $id      * @return membershipfeatures loaded model      * @throws notfoundhttpexception if model cannot found      */     protected function findmodel($id)     {         if (($model = membershipfeatures::findone($id)) !== null) {             return $model;         } else {             throw new notfoundhttpexception('the requested page not exist.');         }     } } 

form :

<?php  use yii\helpers\html; use yii\widgets\activeform; use yii\widgets\pjax; use yii\helpers\url; /* @var $this yii\web\view */ /* @var $model common\models\membershipfeatures */ /* @var $form yii\widgets\activeform */ ?>  <div class="membership-features-form">      <?php $form = activeform::begin([        'enableajaxvalidation' => true,     'enableclientvalidation'=>true,     'validateonsubmit'=>true,        'options' => ['data-pjax'=>true]]); ?>     <?= $form->errorsummary($model); ?>     <?= $form->field($model, 'title')->textinput(['maxlength' => true]) ?>      <?= $form->field($model, 'type')->dropdownlist(['boolean'=>'boolean','value'=>'value'],         [         'onchange'=>'             $.pjax.reload({             url: "'.url::to(['create']).'?type="+$(this).val(),             container: "#pjax-memfeature-form",             timeout: 1000,             });         ',          'class'=>'form-control',         'prompt' => 'select type of value'         ]) ?>          <?php  pjax::begin(['id'=>'pjax-memfeature-form','enablepushstate'=>false]);     ?>          <?php              if($model->type==='boolean'){                 foreach ($membershipplan $key => $value) {                     echo $form->field($model, "value[$key]")->checkbox(array(                                 'label'=>"$value",                                 'labeloptions'=>array('style'=>'padding:5px;'),                                  ));                  }                 }             if($model->type==='value'){                 foreach ($membershipplan $key => $value) {                   echo $form->field($model, "value[$key]")->textinput()->label("$value");                  }             }         ?>           <?php pjax::end(); ?>             <?= $form->field($model, 'is_new')->dropdownlist(['0'=>'no','1'=>'yes']) ?>      <?= $form->field($model, 'status')->dropdownlist(['1'=>'active','0'=>'inactive']) ?>      <div class="form-group">         <?= html::submitbutton($model->isnewrecord ? yii::t('app', 'create') : yii::t('app', 'update'), ['class' => $model->isnewrecord ? 'btn btn-success' : 'btn btn-primary']) ?>          <?= html::a(yii::t('app', 'cancel'), ['/membership-features/'], ['class' => 'btn btn-danger']) ?>     </div>      <?php activeform::end(); ?>  </div> 

i want validate value field dynamically added when change type dropdown using pjax. please guide me correct method validating dynamically added form fields.

its been month guessing has been solved reference others me looking same , save having step thru framework find answer perhaps try like:

... use yii\helpers\json; ...  <?php foreach ($form->attributes $attribute) {     $attribute = json::htmlencode($attribute);     $this->registerjs("jquery('form').yiiactiveform('add', $attribute);"); } ?>  <?php pjax::end(); ?> ... 

tested regards clientvalidation , not above question have hacked solution answer above question.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -