Pass error message from controller to view in zf2

2019-07-27 08:26发布

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条回答
Viruses.
2楼-- · 2019-07-27 09:14

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',
);
查看更多
登录 后发表回答