Learned a lot about my question, and didn't figure it out. I need to write two or more values in the database from checkboxList()
In my view activeForm
<?= $form->field($model, 'quant[]')->checkboxList([
'one' => 'one',
'two' => 'two',
'three' => 'three',
'four' => 'four'],
['separator' => '<br>']); ?>
So after create no matter how much values I choose, only one will add in db. I realized that I need to get an array in the controller and then it will save in the database. Something like this:
public function actionCreate()
{
$model = new TakMol();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->quant=implode(',',$_POST['TakMol']['quant']); //change items into string to be saved
return $this->redirect(['index']);
} else {
$model->quant=explode(',',$model->quant); //string to array to fill the checkboxlist
return $this->render('create', [
'model' => $model,
]);
}
}
Maybe I need to do something like this in 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();
}
I tried and other options, it didn't work out. I will be grateful for help in solving.
If you use a form model as support for extra field for base model, you can handle this task inside this new class.
Put TakMolForm.php file inside the same folder of 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'],
]);
}
}
Then in controller change TakMol in TakMolForm:
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,
]);
}
}
Finally in the view you will use quantArray field instead quant:
<?= $form->field($model, 'quantArray')->checkboxList([
'one' => 'one',
'two' => 'two',
'three' => 'three',
'four' => 'four'],
['separator' => '<br>']); ?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.