I created a checkbox list, i’m facing a problem, when nothing is checked in the checkboxlist, it will show error: (implode(): Argument #2 ($array) must be of type ?array, string given)
How can i solve this? This is my code in the controller.
public function actionCreate()
{
$model = new Amenities();
if(isset($_POST['Amenities']))
{
$model->attributes=$_POST['Amenities'];
if(isset($_POST['Amenities']['Name']) && ($_POST['Amenities']['Name'])!==array())
$model->Name=implode(',',$_POST['Amenities']['Name']);
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
return $this->render('create',[
'model'=>$model,
]);
}
You should take more advantage of what Yii2 offers! Load data from user the Yii2 method: read Yii2 Input Validation
This is easier to read and will prevent many type of attacks your system could suffer.
Basically the error says that the second argument is a string, instead of array, so just make sure it is an array before trying to call the implode method (you are making sure it’s not an empty array).
I would leave this implode to the Amenities Model. This will clean up the code here and give you more consistency when calling this save method.
Here is how I would do it: YourController.php:
public function actionCreate()
{
$model = new Amenities();
if ( $model->load( \Yii::$app->request->post() ) && $model->save() ) {
$this->redirect(array('view','id'=>$model->id));
}
return $this->render('create',[
'model'=>$model,
]);
}
In Amenities.php:
public function beforeSave($insert)
{
if (!parent::beforeSave($insert))
return false;
if (is_array($this->Name)) {
$this->Name = implode(',', $this->Name);
}
return true;
}
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
if (is_string($this->Name)) {
$this->Name = explode(',', $this->Name);
}
}
public function afterFind()
{
parent::afterFind();
if (is_string($this->Name)) {
$this->Name = explode(',', $this->Name);
}
}
This way, it will always perform the implode when saving and always perform the explode after recovering from DB.