Skip to content

Instantly share code, notes, and snippets.

@fieg
Last active October 18, 2023 11:01
Show Gist options
  • Save fieg/33200ecd7aab92641bc4d2cebe2e9037 to your computer and use it in GitHub Desktop.
Save fieg/33200ecd7aab92641bc4d2cebe2e9037 to your computer and use it in GitHub Desktop.
Symfony4 Login Form Type
{% extends 'base.html.twig' %}
{% block body %}
<form action="{{ path('login') }}" method="post">
{{ form_widget(form) }}
{# Note: ensure the submit name does not conflict with the form's name or it may clobber field data #}
<input type="submit" name="login" />
</form>
{% endblock %}
<?php
use LoginType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
final class LoginController extends Controller
{
/**
* @Route("/login", name="login")
* @Template(template="login.html.twig")
*/
public function loginAction()
{
$form = $this->createForm(LoginType::class);
return [
'login_form' => $form->createView(),
];
}
}
<?php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
final class LoginType extends AbstractType
{
/**
* @var AuthenticationUtils
*/
private $authenticationUtils;
public function __construct(AuthenticationUtils $authenticationUtils)
{
$this->authenticationUtils = $authenticationUtils;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('_username', TextType::class)
->add('_password', PasswordType::class)
->add('_target_path', 'Symfony\Component\Form\Extension\Core\Type\HiddenType')
;
$authUtils = $this->authenticationUtils;
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($authUtils) {
// get the login error if there is one
$error = $authUtils->getLastAuthenticationError();
if ($error) {
$event->getForm()->addError(new FormError($error->getMessage()));
}
$event->setData(array_replace((array) $event->getData(), array(
'_username' => $authUtils->getLastUsername(),
)));
});
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
/* Note: the form's csrf_token_id must correspond to that for the form login
* listener in order for the CSRF token to validate successfully.
*/
$resolver->setDefaults(array(
'csrf_token_id' => 'authenticate',
));
}
public function getBlockPrefix()
{
return '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment