如何在yii2中的单个表中多次插入属性值

时间:2017-04-20 10:38:33

标签: yii2

我有一个名叫Taluka的模特。我应该选择区,并为该特定区域输入尽可能多的talukas。每件事都有效,但是当我输入多个talukas时,只有最后一个taluka被保存在数据库表中。我也尝试过Yii2 Insert multiple records of a same table

中给出的解决方案

但我收到的错误是"在数组&#34上调用成员函数isAttributeRequired();

型号:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "taluka".
 *

*/

class Taluka extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */


public $talukas=[];

public static function tableName()
{
    return 'taluka';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['DistrictId', 'Taluka'], 'required'],
        [['DistrictId'], 'integer'],
        [['talukas'], 'required'],
        [['Taluka'], 'string', 'max' => 100],
        [['DistrictId'], 'exist', 'skipOnError' => true, 'targetClass' => District::className(), 'targetAttribute' => ['DistrictId' => 'DistrictId']],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'TalukaId' => 'Taluka ID',
        'DistrictId' => 'District',
        'talukas' => 'Taluka',
    ];
}


/**
 * @return \yii\db\ActiveQuery
 */
 public function getDistrict()
 {
     return $this->hasOne(District::className(), ['DistrictId' => 'DistrictId']);
  }
}

控制器:

 <?php

namespace app\controllers;

use Yii;
use app\models\Taluka;
use app\models\TalukaSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\District;
use app\models\Model;

/**
 * TalukaController implements the CRUD actions for Taluka model.
 */
class TalukaController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Taluka models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new TalukaSearch();
        $dataProvider = $searchModel->search(Yii::$app->request-`>queryParams);`

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Taluka model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Taluka model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {



        $model = new Taluka();



      if ($model->load(Yii::$app->request->post()) ) {


        echo $model->DistrictId;

        $talukalist  = $model->talukas;

        if(is_array($talukalist))
          {
             foreach($talukalist as $v)
              {

              }

           }


        foreach($talukalist as $talukalist)
          {


                //echo $talukalist;

                $model->Taluka = $talukalist;

                echo $model->Taluka;

                $model->save(false);

          }

          //return $this->redirect(['view', 'id' => $model->TalukaId]);

      }

         else {
            return $this->render('create', [
               'model' => $model,


            ]);
        }
    }



    /**
     * Updates an existing Taluka model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->TalukaId]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Taluka model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Taluka model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Taluka the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Taluka::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

查看:

<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use app\models\District;
use yii\helpers\ArrayHelper;
use unclead\multipleinput\MultipleInput;

/* @var $this yii\web\View */
/* @var $model app\models\Taluka */
/* @var $form yii\widgets\ActiveForm */
?>


<div class="taluka-form">

   <?php $form = ActiveForm::begin(['id' => 'dynamic-form', 'layout' => 'horizontal',
    'fieldConfig' => [
        'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
        'horizontalCssClasses' => [
           'label' => 'col-sm-5',
            //'offset' => 'col-sm-offset-2',
            //'wrapper' => 'col-sm-7',
            'error' => '',
            'hint' => '',

        ],
    ],]);?>

<div class="panel panel-primary " > 
<div class="panel panel-heading"><font size="3"><b>Taluka</b></font></div>
<div class="row">
<div class="col-sm-5">

    <?= $form->field($model, 'DistrictId')->dropDownList(ArrayHelper::map(District::find()->all(),'DistrictId','District'), ['prompt' => 'Select District']) ?>
</div>
</div>


<div class="row">
<div class="col-sm-5">

<?php 


echo $form->field($model, 'talukas')->widget(MultipleInput::className(), [
        'max'               => 500,
        'min'               => 1, // should be at least 2 rows
        'allowEmptyList'    => false,
        //'enableGuessTitle'  => true,
        //'addButtonPosition' => MultipleInput::POS_HEADER // show add button in the header
    ]);

?>

</div>
</div>


</div>





    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

1 个答案:

答案 0 :(得分:0)

首先,让我们了解为什么会出现错误"Call to a member function isAttributeRequired() on array"。原因在于rules方法:

public function rules()
{
    return [
        [['DistrictId', 'Taluka'], 'required'],
        [['DistrictId'], 'integer'],
        [['talukas'], 'required'],// <-- This line causes an error. Reqired filed in ActiveRecord model could not be an array.
        [['Taluka'], 'string', 'max' => 100],
        [['DistrictId'], 'exist', 'skipOnError' => true, 'targetClass' => District::className(), 'targetAttribute' => ['DistrictId' => 'DistrictId']],
    ];
}

因此,最好从[['talukas'], 'required']中移除rules()。这是一个自定义字段,因此ActiveRecord逻辑不会检查它。

此外,actionCreate()中存在一个奇怪的逻辑。请注意,您已根据模型Taluka向模型中添加了自定义字段,并且未填写rules(),这是必需的。因此,您不能只将$_POST加载到模型中,并需要遍历talukas为每个创建一条新记录:

public function actionCreate()
{
    $model = new Taluka();
    if ($model->load(Yii::$app->request->post())) {

        $talukaList = $model->talukas;

        if (is_array($talukaList)) {
            foreach ($talukaList as $taluka) {
                $talukaRecord = new Taluka();
                $talukaRecord->DistrictId = $model->DistrictId;
                $talukaRecord->Taluka = $taluka;
                $talukaRecord->save();
            }
        }
        return $this->redirect(['view', 'id' => $talukaRecord->TalukaId]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

我假设TalukaId是一个自动增量主键。保存所有记录后,它会将您重定向到最后创建的taluka。