【发布时间】:2015-08-07 14:46:56
【问题描述】:
我似乎在创建允许复选框列表和嵌套集一起工作的表单输入时遇到了一些问题。
我想要的是和 bookbub 完全一样的东西: http://i.imgur.com/PfpgSf5.jpg
现在在我的数据库中,我的结构如下:
Category table
- id
- name
- parent_id
基本上,我的想法是在 _form 上显示 parent_id 为 null 作为标题(无复选框)的所有内容,以及在适当标题下显示 parent_id 作为复选框的所有内容。
但是,如果我们正在更新用户的首选项,我可以得到的唯一解决方案似乎不允许我已经选中复选框。然而,它确实显示了我想要的东西。到目前为止,这是我所拥有的:
ProfileReader's(ProfileReader 是我的模型,可以扩展用户以保持他们的偏好)_form:
<?php
$primaryCategories = (new Category)->getPrimaryCategories();
//$selectedCategories = yii\helpers\ArrayHelper::map($model->categories, 'id', 'name');
foreach ($primaryCategories as $pc) {
echo '<p>'.$pc->name.'</p>';
if ($pc->subCategories) {
//the following never fully worked. It doesn't automatically check the boxes for relations that
//are already setup. You need to somehow use $model->categories[#] and 'id' for that to work
//echo $form->field($model->categories[#], 'id')->label(false)
echo $form->field($pc, 'subCategories[' . $pc->id . '][]')->label(false)
->checkboxList(yii\helpers\ArrayHelper::map($pc->subCategories, 'id', 'name'),
['separator' => '<p>']);
}
}
?>
ProfileReaderController:
public function actionUpdate()
{
$model = $this->findModel(\Yii::$app->user->identity->id);
if ($model == null) {
$model = new ProfileReader();
$model->user_id = \Yii::$app->user->identity->id;
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
//link the categories to the pen name
$categories = Yii::$app->request->post()['Category']['subCategories'];
$model->unlinkAll('categories', true);
foreach ($categories as $category) {
if ($category)
foreach ($category as $c) {
$c = (new Category)->findOne($c);
$model->link('categories', $c);
}
}
return $this->redirect(['update']);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
个人资料阅读器:
public function getCategories()
{
return $this->hasMany(Category::className(), ['id' => 'category_id'])
->viaTable('user_category', ['user_id' => 'user_id']);
}
有没有人知道我怎样才能做到这一点?在 Yii2 中是否可以使用 activeform?
【问题讨论】:
标签: php yii2 checkboxlist nested-sets active-form