Php db yii2中的复选框列表多项选择?
对我的问题了解了很多,但没有弄明白。我需要从Php db yii2中的复选框列表多项选择?,php,yii2,Php,Yii2,对我的问题了解了很多,但没有弄明白。我需要从checkboxList() 在我看来activeForm <?= $form->field($model, 'quant[]')->checkboxList([ 'one' => 'one', 'two' => 'two', 'three' => 'three',
checkboxList()
在我看来activeForm
<?= $form->field($model, 'quant[]')->checkboxList([
'one' => 'one',
'two' => 'two',
'three' => 'three',
'four' => 'four'],
['separator' => '<br>']); ?>
也许我需要在actionCreate
$post=Yii::$app->request->post();
$checkbox = array_keys ($post);
foreach ($checkbox as $value){
$model = new TakMol();
$model->quant = $model->id;
$model->quant = $value;
$model->save();
}
我尝试了很多其他的选择,但都没有成功。我将非常感谢您帮助我解决这个问题
如果使用表单模型作为对基本模型的额外字段的支持,则可以在这个新类中处理此任务 将TakMolForm.php文件放在TakMol.php的同一文件夹中:
class TakMolForm extends TakMol
{
private $_quantArray;
public function getQuantArray()
{
// Initialize it from 'quant' attribute
if($this->_quantArray == null)
{
$this->_quantArray = explode(',', $this->quant);
}
return $this->_quantArray;
}
public function setQuantArray($value)
{
$this->_quantArray = $value;
}
public function rules()
{
return array_merge(parent::rules(), [
[['quantArray'], 'safe'],
]);
}
}
然后在控制器中以TakMol形式更改TakMol:
public function saveModel($model)
{
// Here is called getQuantArray() getter from TakMolForm model
$model->quant = implode(',', $model->quantArray);
return $model->save();
}
public function actionCreate()
{
$model = new TakMolForm();
if ($model->load(Yii::$app->request->post()) && $this->saveModel($model)) {
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
public function actionUpdate($id)
{
$model = TakMolForm::findOne($id);
if ($model->load(Yii::$app->request->post()) && $this->saveModel($model)) {
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
最后,在视图中,您将使用quantArray字段代替quant:
<?= $form->field($model, 'quantArray')->checkboxList([
'one' => 'one',
'two' => 'two',
'three' => 'three',
'four' => 'four'],
['separator' => '<br>']); ?>
没有正确回答您的问题。您想做什么。当前输出是什么。在CRUD
\u表单
中,我需要在创建表单时选中多个复选框。然后在我的数据库中(在索引GridView
列quant
中相同),我得到输入的值。例如:添加img表格(单元格)我选择Quant:1,3,4
。表单创建后,它只返回一个(第一个)值,添加img索引(cell)。我尝试使用您的答案,在TakMolForm.php中有一个错误:语法错误,意外的'getQuantArray'(T_字符串),期望变量(T_变量)
如果我设置public getQuantArray()
->public$getQuantArray()
返回语法错误,意外的(“,应为“,”或“;”
。我尝试了一些变体,但结果相同。这可能是什么错误?抱歉,我在public之后错过了“function”…因此它是“public function getQuantArray”…为“serQuantArray”做了同样的事情…我已经更新了源代码哦,天哪,它工作得很好!非常感谢!最后在您更新之后。。.Array
我理解代码是如何工作的。还有一个问题,如果在\u表单中的另一个单元格带有复选框()
,我需要v1
:创建一个新的TakMolForm2.php
并在控制器中添加$model=new TakMolForm();
$model=new TakMolForm2();
或v2
:在TakMolForm.php
中,重复private…和两个函数
,但使用其他名称,然后在规则[['quantArray','quantArray'],'safe'],
中,对其他字段重复相同的解决方案
<?= $form->field($model, 'quantArray')->checkboxList([
'one' => 'one',
'two' => 'two',
'three' => 'three',
'four' => 'four'],
['separator' => '<br>']); ?>