Symfony2 getLastUsername() function not working - symfony

I'm creating my first Symfony2 login form and want to use the getLastUsername() function to set the value of the username textbox but when calling the function it simply returns an empty string.
This is my SecurityController.php file:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class SecurityController extends Controller
{
/**
* #Route("/login", name="login")
*/
public function loginAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render(
'security/login.html.twig',
array(
// last username entered by the user
'last_username' => $lastUsername,
'error' => $error,
)
);
}
/**
* #Route("/login_check", name="login_check")
*/
public function loginCheckAction()
{
}
}
?>
and my Twig template for the form:
{# app/Resources/views/security/login.html.twig #}
{% extends 'base.html.twig' %}
{% block stylesheets %}
{{ parent() }}
<link href="{{ asset('css/login.css') }}" rel="stylesheet" />
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('js/login.js') }}"></script>
{% endblock %}
{% block body %}
<div id="container">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
<div id="loginbox">
<form id="loginform" action="{{ path('login_check') }}" method="post">
<p>Enter username and password to continue.</p>
<div class="input-group input-sm">
<span class="input-group-addon"><i class="fa fa-user"></i></span><input class="form-control" type="text" name="_username" id="username" placeholder="Username" value="{{ last_username }}" />
</div>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-lock"></i></span><input class="form-control" type="password" name="_password" id="password" placeholder="Password" />
</div>
<div class="form-actions clearfix">
<div class="pull-left">
Create new account
</div>
<div class="pull-right">
Lost password?
</div>
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}" />
<input type="submit" class="btn btn-block btn-primary btn-default" value="Login" />
</div>
</form>
</div>
</div>
{% endblock %}
Everything works fine. Logged in and out many times but the las username isn't showing. Thought Symfony might be using cookies to save the last used username but it isn't creating any cookies, only the PHP session is saved in a cookie. Is it a problem in the cookie configurations or may be something else?
Thanks,

Related

Symfony simple login

i to do login in my webpage about symfony documentation example and i have a little problem. It's work but work a second time, after i clear cache. In first time i catch error with your session time out or you disabled cookie.
it's base.html.twig
{% if is_granted('ROLE_USER') %}
<div class="content">
<div class="starter-template">
{% block body %}{% endblock %}
</div>
</div>
{% else %}
<div class="container">
<div class="row">
<div class="col-md-offset-5 col-md-3">
<div class="form-login">
<h4>Welcome back.</h4>
<form action="{{ path('login') }}" method="post">
<input type="text" name="_username" id="userName" class="form-control input-sm chat-input" placeholder="username" />
</br>
<input type="password" name="_password" id="userPassword" class="form-control input-sm chat-input" placeholder="password" />
</br>
<div class="wrapper">
<span class="group-btn">
<button type="submit" href="#" class="btn btn-primary btn-md">login <i class="fa fa-sign-in"></i></button>
</span>
</div>
</form>
</div>
</div>
</div>
</div>
{% endif %}
and login action:
/**
* #Route("/login", name="login")
*/
public function loginAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
));
}
I try return redirect in this action but nothing helps me.
If login to do in /login page it's work okey. But I want use with which construction how in base.html
Try work on dev mode.
1) Go on web directory
2) Open app.php file
3) Change the code inside app.php to
$kernel = new AppKernel('dev', true);
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Remove from controller
/**
* #Route("/login", name="login")
*/
Finally try move route in routing file.
For example in routing.yml:
login:
path: /login
defaults: { _controller: YourNameBundle:NameYourController:login }

FOSUserBundle. Include login form in my template

Hi I'm trying to include the login form of the FOSUser Bundle in my custom template. Like that:
{% include 'FOSUserBundle:Security:login.html.twig' %}
But I have this error:
Variable "error" does not exist in FOSUserBundle:Security:login.html.twig at line 7
Is there a way to include the template without adding something in my controller?
To overriding FosUserBundle's template you have to do this :
Create a folder FOSUserBundle/view in app/Resources
Copy the view folder of FOSUserBundle in your folder you have create just before
And you can include your template and custom FOSUser view.
Example :
layout.html.twig of FOSUser in app/Resources/FOSUserBundle/view:
{% extends ":layout:Public/layout.html.twig" %} #My layout
{% block body %}
<div>
{% block fos_user_content %}
{% endblock fos_user_content %}
</div>
{% endblock %}
And app/Resources/FOSUserBundle/view/Security/login.html.twg :
{% extends "FOSUserBundle::layout.html.twig" %}
{% trans_default_domain 'FOSUserBundle' %}
{% block fos_user_content %}
<div class="col-md-4">
<form action="{{ path("fos_user_security_check") }}" method="post">
<h2 class="form-signin-heading">Se connecter </h2>
<hr>
<input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />
<label class="sr-only" for="username">{{ 'security.login.username'|trans }}</label>
<input class="form-control" type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
<label class="sr-only" for="password">{{ 'security.login.password'|trans }}</label>
<input class="form-control" type="password" id="password" name="_password" required="required" placeholder="Mot de passe" />
<div class="checkbox">
<label>
<input type="checkbox" id="remember_me" name="_remember_me" value="on" />
<label for="remember_me">{{ 'security.login.remember_me'|trans }}</label>
</label>
</div>
<input class="btn btn-primary" type="submit" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans }}" />
</form>
<br>
Mot de passe perdu ?
</div>
<div class="col-md-2"></div>
<div class="col-md-3">
<h2>Pas encore inscrit ?</h2>
<hr>
<em>
nous vous invitons à vous inscrire<br />
</em>
<br /><br />
S'inscrire
</div>
{% endblock fos_user_content %}
I think there is many solutions, but according to me it's the better way to overrinding fosuser's views
This template is expected to be rendered as a full page. To include it, it might be more convenient to render the controller action.
{{ render(controller('FOSUserBundle:Security:login')) }}

Sonata Admin : Forgotten Password

I am using Sonata Admin with SonataUser/FosUser bundles.
I want to integrate the "reset password" functionality from FosUser into Sonata. Is there a quick way to :
integrate the "forgot your password" link into the sonata login page ?
integrate the functionality with the "admin/" url prefix and the sonata html/twig layout ?
I have modified the admin login template to add the reset password link, you must extend the SonataUserBundle in order to use your custom template, follow the documentation.
The custom template must have the same name and the same directory as in SonataUserBundle. Here is the template I used :
Application\Sonata\UserBundle\Resources\views\Admin\Security\login.html.twig
{% extends base_template %}
{% block content %}
<div class="connection">
<form action="{{ path("sonata_user_admin_security_check") }}" method="post">
{% if error %}
<div class="alert alert-error">{{ error|trans({}, 'SonataUserBundle') }}</div>
{% endif %}
<input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />
<div class="control-group">
<label for="username">{{ 'security.login.username'|trans({}, 'FOSUserBundle') }}</label>
<div class="controls">
<input type="text" id="username" name="_username" value="{{ last_username }}" class="big sonata-medium"/>
</div>
</div>
<div class="control-group">
<label for="password">{{ 'security.login.password'|trans({}, 'FOSUserBundle') }}</label>
<div class="controls">
<input type="password" id="password" name="_password" class="big sonata-medium" />
</div>
</div>
<div class="control-group">
<label for="remember_me">
<input type="checkbox" id="remember_me" name="_remember_me" value="on" />
{{ 'security.login.remember_me'|trans({}, 'FOSUserBundle') }}
</label>
</div>
<div class="control-group">
<a href="{{ path('fos_user_resetting_request') }}">
{{ 'forgotten_password'|trans({}, 'SonataUserBundle') }}
</a>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans({}, 'FOSUserBundle') }}" />
</div>
</form>
</div>
{% endblock content %}

how to create a customized form

I'm working in a project and I would like to create form and not using form_widget. I want to create my own form.
Here is my controller:
public function newAction()
{
$entity = new Etudiant();
$form = $this->createCreateForm($entity);
return $this->render('MyAppRevBundle:Etudiant:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
And my html page is:
{% extends '::base.html.twig' %}
{% block body -%}
<form action="{{ path('etudiant') }}" {{form_enctype(form)}} method="post" >
<label for="username" class="col-md-2 control_label">Login :</label>
<input type="text" id="username" name="_username" value="Thaer"required="required" />
<br>
<input type="submit"/>
{{ form_rest(form) }}
</form>
<ul class="record_actions">
<li>
<a href="{{ path('etudiant') }}">
return
</a>
</li>
</ul>
{% endblock %}
so i solved
so it should be
{% extends '::base.html.twig' %}
{% block body -%}
<form action="{{ path('etudiant') }}" {{form_enctype(form)}} method="post" >
<table>
<tr>
<td>Libelle: </td>
<td>{{ form_widget(form.libelle)}}
</tr>
</table>
< input type="submit" />
{{ form_rest(form) }}
</form>
<ul class="record_actions">
<li>
<a href="{{ path('etudiant') }}">
return
</a>
</li>
{% endblock %}

Django styling login forms and adding additional spans

I have two questions in form-styling.
For my login, I am using Django's default auth features and haven't written any views or forms manually.
urls.py
urlpatterns += patterns(
'django.contrib.auth.views',
url(r'^login/$','login',
{'template_name':'login.html'},
name='qna_login'),
url(r'^logout/$','logout',
{'next_page':'qna_home'},
name='qna_logout'),
)
login.html
{% extends "base.html" %}
{% block content%}
{% if form.errors %}
<p class="text-warning"> Your username and/or password didn't match </p>
{% endif%}
<form role="form" class="form-horizontal" method="post" action="{% url 'django.contrib.auth.views.login' %}">
<div class="form-group">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-primary" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
{% endblock %}
How do I add bootstrap styling to it?
For new user registration, I have added some bootstrap specific styles, but need to add additional spans and replace the labels with Glyphicons.
forms.py
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password')
def __init__(self, *args, **kwargs):
super(UserForm,self).__init__(*args,**kwargs)
self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Username'})
self.fields['email'].widget.attrs.update({'class':'form-control','placeholder':'Email'})
self.fields['password'].widget.attrs.update({'class':'form-control','placeholder':'Password'})
What I need to do is replace what is generated in the template, such as
<p><label for="id_username">Username:</label> <input class="form-control" id="id_username" maxlength="30" name="username" placeholder="Username" type="text" /> <span class="helptext">Required. 30 characters or fewer. Letters, numbers and #/./+/-/_ characters</span></p>
by a custom bootstrap addon and glyphicon, like
<div class="input-group">
<span class="input-group-addon" style="background-color:#b77b48; color:white"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" class="form-control" placeholder="Username">
</div>
You can render each field individually instead of letting Django render the whole form with {{ form }}. You can write the template like this -
<form role="form" class="form-horizontal" method="post" action="{% url 'django.contrib.auth.views.login' %}">{% csrf_token %}
<div class="form-group">
{% for field in form %}
<div class="input-group">
<span class="input-group-addon" style="background-color:#b77b48; color:white"><span class="glyphicon glyphicon-user"></span></span>
<input class="form-control" id="{{ field.id_for_label }}" maxlength="30" name="{{ field.html_name }}" value="{{ field.value }}" type="text" />
{{ field.errors }}
</div>
{% endfor %}
<input type="submit" class="btn btn-primary" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
As always, like everything else, Django documentation has everything.

Resources