Simple Symfony Login Form Example
There are times when I just need a simple login form that checks for a certain username and password combination in order to lockdown a backend administration interface. The new sfForm sub-framework in Symfony 1.1/1.2 makes it really easy to reuse a Form class for this. If you’re unfamiliar with the new sfForm sub-framework, you should probably start with the Forms Book. Here’s an example form (placed in lib/form):
<?php
class LoginForm extends sfForm
{
public function configure()
{
$this->setWidgets(array(
'username' => new sfWidgetFormInput(),
'password' => new sfWidgetFormInputPassword()
));
$this->widgetSchema->setNameFormat('login[%s]');
$this->setValidators(array(
'username' => new sfValidatorChoice(array('required' => true, 'choices' => array('admin'))),
'password' => new sfValidatorChoice(array('required' => true, 'choices' => array('some_password')))
));
}
}
The key here is using sfValidatorChoice to ensure that the input matches some predefined keys (“admin” and “some_password” in this case).
For completeness, here’s the action file:
<?php
class authActions extends sfActions
{
public function executeLogin(sfWebRequest $request)
{
$this->form = new LoginForm();
if ($request->isMethod('post'))
{
$this->form->bind($request->getParameter('login'));
if ($this->form->isValid())
{
// authenticate user and redirect them
$this->getUser()->setAuthenticated(true);
$this->getUser()->addCredential('user');
$this->redirect('home/index');
}
}
}
public function executeLogout()
{
$this->getUser()->clearCredentials();
$this->getUser()->setAuthenticated(false);
$this->redirect('@homepage');
}
}
And the template file loginSuccess.php:
<form action="<?php echo url_for('auth/login') ?>" method="POST">
<table>
<?php echo $form ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
And of course, you’ll want to turn on security for the application in security.yml:
default:
is_secure: on
credentials: user
Find This Article Useful?
Related Articles
About this entry
You’re currently reading “Simple Symfony Login Form Example,” an entry on MirthLab
- Published:
- Tuesday, November 18th, 2008 at 12:25 pm
- Author:
- Mark Quezada
- Category:
- Web Development
- Tags:
- forms, symfony, symfony 1.2

9 Comments
Jump to comment form | comments rss | trackback uri