Yii2 Select2 - 更新时选择的值 - 联结表(多对多)
Posted
技术标签:
【中文标题】Yii2 Select2 - 更新时选择的值 - 联结表(多对多)【英文标题】:Yii2 Select2 - selected value on update - junction table (many to many) 【发布时间】:2017-01-18 18:06:54 【问题描述】:我在操作创建时成功地在我的联结表(用户位置)中插入了新行,并且我在操作更新时成功更新了它们,但问题是在更新时 location_id 字段始终为空。它应该从 userlocations 表中检索 location_id 并在更新时填充该字段,但它没有。
数据库:http://i.stack.imgur.com/JFjdz.png
用户控制器:
<?php
namespace backend\controllers;
use Yii;
use backend\models\User;
use backend\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use backend\models\Locations;
use backend\models\Userlocations;
class UserController extends Controller
public function behaviors()
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
/**
* Lists all User models.
* @return mixed
*/
public function actionIndex()
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
/**
* Displays a single User model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
return $this->render('view', [
'model' => $this->findModel($id),
]);
/**
* Creates a new User model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
$model = new User();
$locations = ArrayHelper::map(Locations::find()->all(), 'id', 'name');
$userlocations = new Userlocations();
if ($model->load(Yii::$app->request->post()) )
$model->setPassword($model->password);
$model->generateAuthKey();
$userlocations->load(Yii::$app->request->post());
if ($model->save() && !empty($userlocations->location_id))
foreach ($userlocations->location_id as $location_id)
$userlocations = new Userlocations();
$userlocations->setAttributes([
'location_id' => $location_id,
'user_id' => $model->id,
]);
$userlocations->save();
return $this->redirect(['user/index']);
else
return $this->render('create', [
'model' => $model,
'locations' => $locations,
'userlocations' => $userlocations,
]);
/**
* Updates an existing User 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);
$locations = ArrayHelper::map(Locations::find()->all(), 'id', 'name');
$userlocations = new Userlocations();
if ($model->load(Yii::$app->request->post()) && $model->save())
Userlocations::deleteAll(['user_id' => $id]);
$userlocations->load(Yii::$app->request->post());
if (!empty($userlocations->location_id))
foreach ($userlocations->location_id as $location_id)
$userlocations = new Userlocations();
$userlocations->setAttributes([
'location_id' => $location_id,
'user_id' => $model->id,
]);
$userlocations->save();
return $this->redirect(['user/index']);
else
return $this->render('update', [
'model' => $model,
'locations' => $locations,
'userlocations' => $userlocations,
]);
/**
* Deletes an existing User 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 User model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return User the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
if (($model = User::findOne($id)) !== null)
return $model;
else
throw new NotFoundHttpException('The requested page does not exist.');
用户模型:
class User extends \common\models\User
public $password;
/**
* @inheritdoc
*/
public static function tableName()
return 'User';
/**
* @inheritdoc
*/
public function rules()
return [
[['username', 'password'], 'required'],
[['status', 'created_at', 'updated_at'], 'integer'],
[['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['username'], 'unique', 'message' => 'Username already taken!'],
[['email'], 'unique'],
[['password_reset_token'], 'unique'],
];
/**
* @inheritdoc
*/
public function attributeLabels()
return [
'id' => 'ID',
'username' => 'Username',
'auth_key' => 'Auth Key',
'password_hash' => 'Password Hash',
'password_reset_token' => 'Password Reset Token',
'email' => 'Email',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
我的表格:
<?php
use yii\helpers\html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
use backend\models\Locations;
?>
<div class="user-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
<?= $form->field($userlocations, 'location_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Locations::find()->all(), 'id', 'name'),
'size' => Select2::MEDIUM,
'options' => ['placeholder' => 'Select a location ...', 'multiple' => true],
'pluginOptions' => [
'allowClear' => true,
],
]); ?>
<?= $form->field($model, 'status')->dropDownList(['10' => 'Active', '0' => 'Inactive']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
【问题讨论】:
@PurpleHaze 你能告诉我你的用户模型吗?我在用户表中看不到 location_id 字段 显示发送到服务器的帖子数据的快照。您可以使用 chrome 开发人员工具中的网络选项卡查看您的帖子数据 如果您在多个表中进行更改,请始终在事务中使用它 @KiranMuralee 我做了一些小的改动试图让它工作,但结果是一样的。我还更新了完整的用户模型用户控制器和用户表单。这是我发送到服务器的帖子数据:oi65.tinypic.com/okspwk.jpg 谢谢,我会调查的 【参考方案1】:对于多个位置选择,请使用下面给出的插件代码。
<?= Select2::widget([
'name' => 'Userlocations[location_id]',
'value' => $location_ids, // initial value
'data' => ArrayHelper::map(Locations::find()->all(), 'id', 'name'),
'options' => ['placeholder' => 'Select your locations...', 'multiple' => true],
'pluginOptions' => [
'tags' => true,
'maximumInputLength' => 10
],
]); ?>
$location_ids 将是您之前在创建期间选择的位置数组。另外请记住,当您对多个表进行更改时,请确保在事务中进行。
【讨论】:
非常感谢基兰:D以上是关于Yii2 Select2 - 更新时选择的值 - 联结表(多对多)的主要内容,如果未能解决你的问题,请参考以下文章
Yii2:带有 jQuery 事件的 select2 不起作用
从 javascript 设置 yii2 select2 小部件的值