[英]get value from checkboxlist yii2
這里我有2個視圖,第一個視圖是一個讓用戶注冊的表單。 然后將信息保存到控制器中的DB並參考其他視圖。
我在第一個視圖中寫了一個復選框列表。
<?= $form->field($model, 'items[]')->checkboxList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']); ?>
然后我試圖從控制器中獲取它的值並保存到DB。
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
//save to DB
$model = new EntryForm();
$tableMember=new Members;
$tableMember->select=$model-> items ;
$tableMember->save();
return $this->render('entry-confirm', ['model' => $model]);
}
在entry-confirm.php中顯示
<li><label>Selected</label>: <?php echo Html::encode($model->items['a']) ?></li>
但它是空的。
我使用NetBeans調試器,它顯示:
$_POST = [
'_csrf' => 'OTFHYUpIaVJNSxAJPBEDGV8DcTYjAhojAFofVx0HJmULVCwoAiRENA==',
'EntryForm' => [
'username' => 'df',
'email' => '2@c.c',
'password' => '123',
'items' => [
'a',
'b',
],
'country' => '',
],
];
似乎項目確實獲得了屬性。 有沒有其他方法來創建復選框? 或者我如何從復選框列表中獲取值?
試試這種方式:
<?php
echo $form->checkBoxList($model,'items',
array('a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C'),
);
?>
此復選框列表應該是表單窗口小部件的一部分,而項目應該是您的數據庫字段或類中的變量。首先嘗試檢查您的模型字段是否出現在您的視圖中。
試試這個吧
$tableMember->select = implode(",", $model-> items);
$model->items
返回已選中復選框的數組。
好吧,我總是遇到類似問題的問題
$model->items
(如復選框列表中的值),我發現使用例如$_POST['EntryForm']['items']
獲取值更容易,如下所示:
$model->items=implode(',',$_POST['EntryForm']['items']);
(在$model->save()
之前在控制器中完成)
舉個例子:
(我們拆分帖子並保存動作)
if ($model->load(Yii::$app->request->post())) {
$model->items=implode(',',$_POST['EntryForm']['items']); //change items into string to be saved
if($model->save()){
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
$model->items=explode(',',$model->items); //string to array to fill the checkboxlist
return $this->render('create', [
'model' => $model,
]);
}
$ model->項目不起作用的主要問題是它可能不被認為是“安全的”,這意味着它沒有在規則下的模型中聲明(公共函數規則(),例如添加
[['items'], 'string', 'max' => 250],
要么
[['items'], 'safe'],
應該做的伎倆....
另見: Yii2 - 模型 - 安全屬性
HTH
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.