开发者

A better way of passing variables from controller to view in symfony

开发者 https://www.devze.com 2023-02-07 13:17 出处:网络
Hey. I\'ve got a login form with post as method. The action goes to \'auth/login\' and will check the database if the user exists. If the user exists, I call the$this->getUser->setAuthenticated(true);

Hey. I've got a login form with post as method. The action goes to 'auth/login' and will check the database if the user exists. If the user exists, I call the $this->getUser->setAuthenticated(true);. After this I want to redirect to a welcome page if success.

If the login failed, I would want to tell the user so in the view of course. But settings variables in the controller only if login failed, and check in the view if each of those variables are set, is a lot of work?

This means I ha开发者_如何转开发ve to check almost all variables I want to use in the view set from the controller. If it should happen that it is not set, and I just go ahead and echo it, I get an error from symfony, and production stage-mode-ish don't show anything but an 500 internal server error .

Thanks

EDIT:

This is my current, new and better solution. Still looking for feeback.

in /templates/loginSuccess

if ($sf_params->has('bad_login')) { echo "Wrong username or password"; }

And in my controller:

$this->redirect('auth/login?bad_login=');


Take a look at how sfDoctrineGuardPlugin (the de-facto standard for authentication) does it: they created sfGuardValidatorUser and use it as a post validator in the signin form.

Advantage of this method: the form takes care of the username/password validation, you do not need to put that code in your action. It simplifies that to a simple $form->isValid() { $this->redirect("@homepage"); }.


It seems like you could use symfony's form to take care of the validation. Since the forms show errors built in, you could put this into the form validation and then your controller looks something like:

$form = new LoginForm;
if ($request->isMethod('post')) 
{
  if ($form->isValid())
  {
    $this->redirect('account');
  }
  else
  {
    // this would show the form, and since you put the login in the form validation it will show errors. You could have the username show the error
  }
}

To do what you are doing though, I'd recommend this. That way you aren't accessing any parameters in the view as well.

Controller:

$this->bad_login = $this->getParameter('bad_login',false);

View:

if ($bad_login) { echo 'bad login'; }


  1. Use forward()
  2. Put all the logic required for the view population into separate method of a controller, and call it in both places.
  3. Use cgratigny's solution - put login form and processing code in a single action, and redirect to welcome page if isMethod('post') && $login_success
0

精彩评论

暂无评论...
验证码 换一张
取 消