I have this in Controller, generated with giiant (I assume it's correct):
public function actionDelete($id) {
try {
$this->findModel($id)->delete();
} catch (\Exception $e) {
$msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
\Yii::$app->getSession()->addFlash('deleteError', $msg);
return $this->redirect(Url::previous());
}
$isPivot = strstr('$id', ',');
if ($isPivot == true) {
return $this->redirect(Url::previous());
} elseif (isset(\Yii::$app->session['__crudReturnUrl']) && \Yii::$app->session['__crudReturnUrl'] != '/') {
Url::remember(null);
$url = \Yii::$app->session['__crudReturnUrl'];
\Yii::$app->session['__crudReturnUrl'] = null;
return $this->redirect($url);
} else {
return $this->redirect(['index']);
}
}
Now my problem is, that it throws sometimes $msg
as array and I have no clue why.
View/index:
if (\Yii::$app->session->getFlash('deleteError') !== null) {
echo Alert::widget([
'options' => ['class' => 'alert-danger'],
'body' => \Yii::$app->session->getFlash('deleteError'),
])
;}
The error message:
PHP Notice – yii\base\ErrorException
Array to string conversion
I have no clue why is it sometimes array and sometimes not. All controllers are the same, but for some Models it's working, for some not. I can implement a workaround that if is_array then ...[0] otherwise ...
but I feel it's not the right way to solve the problem. How can a Model change the data type of this error message? Can you please point me to the right direction? Many thanks.
First, you're actually never using model validation here, so it has nothing to do with model. Second, $msg
is probably OK, the problem is how you're using getFlash()
. This method may return array, this is expected and documented:
The flash message or an array of messages if addFlash was used.
You should either iterate trough getFlash()
result to get actual message as string, or use widget which will handle this and generate multiple alerts from getFlash()
result.
You may also use setFlash()
instead of addFlash()
. But I would not recommend this - it is easy override some previous flashes and you should not blindly assume that getFlash()
result will be a string.