Pass error message from controller to view in zf2

末鹿安然 提交于 2019-12-11 06:57:50

问题


I have simple login in zf2. I want to show error message error to user when username/password didn't match.

In view/login.php:

    if (isset($error_msg))
    {
    echo $error_msg;
    } 

In Controller I have:

$msg = array('error_msg' => 'Invalid Username or Password');
return $this->redirect()->toRoute('login', $msg);

Here error_msg cannot passed to view, what are wrong with this?

Furthermore I also try

$model = new ViewModel(array(
    'error_msg' => 'Wrong username or password',
));
$model->setTemplate('login/index');  
return $model; 

But here link didn't go to login/index. but instead go to login/process. Process is the action in which login is processed.

Help me friends please. I want to pass error message from controller to view . So how should I do it.


回答1:


Just put your login process code into your login index action, there's no need to have two actions for this. When you have processed your login and determined that it has failed simply pass your error message to your view model and display it in your view. This can be done in several ways.

$viewModel = new ViewModel();
$viewModel->error_msg = 'Wrong username or password';
return $viewModel;

return new ViewModel(array(
    'error_msg' => 'Wrong username or password',
));

or simply

return array(
    'error_msg' => 'Wrong username or password',
);


来源:https://stackoverflow.com/questions/42318604/pass-error-message-from-controller-to-view-in-zf2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!