php - Yii2 give array fields names and save to database -
can give each item saved array , database name.
for example have 3 form fields saved same array. can setup fields below or if below not correct best way it?
echo $form->field($model, 'arrayfields')->textinput([ 'name'=>'field1inarray[]', ]); echo $form->field($model, 'arrayfields')->textinput([ 'name'=>'field2inarray[]', ]); echo $form->field($model, 'arrayfields')->textinput([ 'name'=>'field3inarray[]', ]);
also how go saving array database in controller/model?
i used below in view
<?= $form->field($model, 'example[arrayfield1]')->textinput(['maxlength' => 255])->label('array field 1') ?> <?= $form->field($model, 'example[arrayfield2]')->textinput(['maxlength' => 255])->label('array field 2') ?>
and within controller save database did following
public function actioncreate() { $model = new somemodel(); if ($model->load(yii::$app->request->post())) { $array = $_post['somemodel']['example']; $model->stockists = json_encode($array); $model->save(); return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } }
open code improvements, need add validation check whether or not post value exists.
now need work way value populated in update form.
Comments
Post a Comment