如何在更新时从yii2中的数组对象设置多重选择值 [英] How to set multi select value from array object in yii2 while updating
问题描述
我有一个表,该表对
user
id name email
categories
id title
user_categories
user_id category_id
在此,用户将具有与其关联的多个类别
Here a user will have multiple category associated with him/her
我能够使用如下所示的新记录成功保存这些
I am able to save these successfully with new records like following
查看文件:
echo $form->field($package_categories, 'category_id')->dropDownList( ArrayHelper::map(
StudyMaterialCategories::find()->all(), 'id', 'title'),
['multiple' => true]
);
保存新记录:
$model = new Packages();
$package_categories = new PackageCategories();
$request = Yii::$app->request;
if ($request->isPost) {
$transaction = Yii::$app->db->beginTransaction();
try {
$post = $request->post();
$model->load($post);
$model->save();
foreach ($post['PackageCategories']['category_id'] as $key => $value) {
$package_categories = new PackageCategories();
$package_categories->category_id = $value;
$package_categories->package_id = $model->id;
$package_categories->save();
}
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
} catch (Exception $ex) {
$transaction->rolback();
Yii::$app->session->setFlash("error", $ex->getMessage());
}
}
到目前为止,它正在成功运行.
Till now It's running successfully.
但是当我要更新表时,我被卡住了.问题部分是下拉列表.如果要使用对象数组,如何根据数据库设置多个选定的选项. 看看下面的代码
But I'm stuck when going to update the table. The problem part is dropdown list. How to set multiple selected option as per database if I'm coming with array of object. Have a look on the following code
$package_categories = PackageCategories::find()
->where('package_id=:package_id', ['package_id' => $id])->all();
if (count($package_categories) < 1) {
$package_categories = new PackageCategories();
}
$request = Yii::$app->request;
if ($request->isPost) {
$transaction = Yii::$app->db->beginTransaction();
try {
$post = $request->post();
$model->load($post);
$model->save();
$package_categories = new PackageCategories();
$package_categories->deleteAll(
"package_id=:package_id",
[':package_id' => $model->id]
);
foreach ($post['PackageCategories']['category_id'] as $key => $value) {
$package_categories = new PackageCategories();
$package_categories->category_id = $value;
$package_categories->package_id = $model->id;
$package_categories->save();
}
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
} catch (Exception $ex) {
$transaction->rolback();
Yii::$app->session->setFlash("error", $ex->getMessage());
}
}
如果我尝试获取只能设置所选一个选项的数组$package_categories
的第一个对象
if I try to get first object of the array $package_categories
of only able to set selected one option
推荐答案
这是模型类Permit
的示例代码,该类与Activity
到PermitActivity
(数据透视表模型)具有many to many
关系.
This is an example code of a model class Permit
which has a many to many
relationship with Activity
through PermitActivity
(pivot table model).
模型课堂活动
public class Permit extends \yii\db\ActiveRecord {
public $activities_ids;
...
public function rules() {
return [
...
[['activities_ids'], 'safe'],
...
];
}
...
// Method called after record is saved, be it insert or update.
public function afterSave($insert, $changedAttributes) {
// If this is not a new record, unlink all records related through relationship 'activities'
if(!$this->isNewRecord) {
// We unlink all related records from the 'activities' relationship.
$this->unlinkAll('activities', true);
// NOTE: because this is a many to many relationship, we send 'true' as second parameter
// so the records in the pivot table are deleted. However on a one to many relationship
// if we send true, this method will delete the records on the related table. Because of this,
// send false on one to many relationships if you don't want the related records deleted.
}
foreach($this->activities_ids as $activity_id) {
// Find and link every model from the array of ids we got from the user.
$activity = Activity::findOne($activity_id);
$this->link('activities', $activity);
}
parent::afterSave($insert, $changedAttributes);
}
...
// Declare relationship with Activity through the pivot table permitActivity
public function getActivities(){
return $this->hasMany(Activitiy::className(), ['id' => 'activity_id'])
->viaTable('permitActivity',['permit_id' => 'id']);
}
...
public function afterFind(){
parent::afterFind();
$this->activities_id = ArrayHelper::getColumn($this->activities, 'id');
}
}
这样,模型类就是负责使用数据透视表创建和更新关系的类.
This way the model class is the one responsible for creating and updating the relationship using the pivot table.
最重要的是正确声明关系方法.
The most important thing is to have the relationship method declared correctly.
修改
这是使用 kartikv\widgets\Select2
的视图的示例.我真的不知道dropDownList是否支持多个选择,但是Select2具有这么多有用的功能,我通常会在其他选项上使用它.
This is an example of the view using kartikv\widgets\Select2
. I don't really know if dropDownList supports multiple select, however Select2 has so many useful features i usually use it over other options.
echo $form->field($model, 'activities')->widget(Select2::classname(), [
'data' => $data,
'options' => [
'placeholder' => '...'
],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
],
]);
这篇关于如何在更新时从yii2中的数组对象设置多重选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!