Add telephone field to FOSUserBundle in symfony 2.7 - symfony

Hi I'm trying to add new field (Telephone) to my FOS User bundle registration form. But Instead of getting this field I'm having this issue.
Method "telephone" for object "Symfony\Component\Form\FormView" does
not exist in FOSUserBundle:Registration:register_content.html.twig at
line 32
I'm trying to override custom templates and add new telephone field(Needed to customise to add few styles....).
\app\Resources\FOSUserBundle\views\Registration\register_content.html.twig
This is my 'register_content.html.twig' template,
{% trans_default_domain 'FOSUserBundle' %}
<div class="container">
<h1 style="text-align: center;">Register a User</h1>
<br>
{{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register'), 'attr': {'class': 'fos_user_registration_register form-horizontal'}}) }}
{# {{ form_widget(form) }}#}
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Username</label>
<div class="col-sm-4">
{{ form_widget(form.username, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors(form.username) }}
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
{{ form_widget(form.email, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors(form.email) }}
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Telephone</label>
<div class="col-sm-4">
{{ form_widget(form.telephone, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors(form.telephone) }}
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-4">
{{ form_widget (form.plainPassword.first, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors (form.plainPassword.first) }}
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Repeat password</label>
<div class="col-sm-4">
{{ form_widget (form.plainPassword.second, { 'attr': {'class': 'form-control'} }) }}
{{ form_errors (form.plainPassword.second) }}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-default" value="{{ 'registration.submit'|trans }}" />
</div>
</div>
{{ form_end(form) }}
</div>
And this is my User Entity,
<?php
// src/AppBundle/Entity/User.php
namespace AdminBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="telephone", type="text", length=30, nullable=false)
*/
private $telephone;
/**
* Set nonotification
*
* #param text $telephone
* #return User
*/
public function settelephone($telephone) {
$this->telephone = $telephone;
return $this;
}
/**
* Get telephone
*
* #return text
*/
public function gettelephone() {
return $this->telephone;
}
public function __construct() {
parent::__construct();
// your own logic
}
}

The form provided by FosUserBundle isn't aware of your new field.
You should add a formtype with the extra fields you created.
Example:
class UserType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('Telephone');
// Other fields
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
// Or for Symfony < 2.8
// return 'fos_user_registration';
}
// other methods needed setDefaultOptions() and getName()
You can find more information at the official documentation: http://symfony.com/doc/current/bundles/FOSUserBundle/overriding_forms.html

Related

login root path / on symfony instead /login

<!-- templates/bootstrap/login/form-login.html.twig-->
<div class="container">
<div class="row">
<div style="padding-right: 0px;" class="col-12">
<form method="post">
<label for="inputEmail">Email</label>
<input type="email" value="{{ last_username }}" name="email" id="inputEmail" class="form-control" autocomplete="email" required autofocus>
<label for="inputPassword">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" autocomplete="current-password" required>
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{% if app.user %}
<div style="margin-top: 10px;" class="mb-3">
You are logged in as {{ app.user.username }}, Logout
</div>
{% endif %}
<button style="margin-top: 10px; width: 100%;" class="btn btn-primary" type="submit">
Sign in
</button>
</form>
<div style="border-top: 1px solid black; height: 1px;margin-top: 10px;"></div>
<a style="width: 100%;" href="/registration" class="btn btn-outline-primary">Create an account</a>
<div style="height: 1px;margin-bottom: 10px;"></div>
</div>
</div>
</div>
All work correctly on "http://webserver5.com:8001/login" path.
But It doesn't work on "http://webserver5.com:8001/" path.
If I enter email and password correctly or incorrectly I obtain only refresh page. Why?
I want "/" root path because to point a login method controller.
Can you help me please.
<?php
namespace App\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'app_welcome';
private $urlGenerator;
public function __construct(UrlGeneratorInterface $urlGenerator)
{
$this->urlGenerator = $urlGenerator;
}
public function authenticate(Request $request): PassportInterface
{
$email = $request->request->get('email', '');
$request->getSession()->set(Security::LAST_USERNAME, $email);
return new Passport(
new UserBadge($email),
new PasswordCredentials($request->request->get('password', '')),
[
new CsrfTokenBadge('authenticate', $request->get('_csrf_token')),
]
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
return new RedirectResponse($targetPath);
}
// For example:
return new RedirectResponse($this->urlGenerator->generate('app_contact_index'));
//throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
}
protected function getLoginUrl(Request $request): string
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}
public const LOGIN_ROUTE = 'app_welcome';
This route app_welcome is defined thus:
/
App\Controller\SecurityController::login
Now it works.

How to use template form when edit object

I have a form with an embedded form (collectionType). I made a template. It works when I add a new object. But how to use this template when I edit an object ? Below my code an 2 pictures to illustrate my problem
{% extends 'base.html.twig' %}
{% form_theme form _self %}
{% block _paris_rencontres_row %}
<div class="sports" id="renc-xx" style="background-color: rgba(182, 184, 185, 0.200);">
<div
class="row">
{# <ul class="sports" data-prototype="{{ form_widget(form.vars.prototype)|e('html_attr') }}"></ul> #}
<div class="col-md-3">
{{ form_row(form.vars.prototype.playedAt) }}
</div>
<div class="col-md-3">
{{ form_row(form.vars.prototype.sport) }}
</div>
</div>
<div class="row">
<div class="col-md-3">
{{ form_row(form.vars.prototype.player_1) }}
</div>
<div class="col-md-3">
{{ form_row(form.vars.prototype.player_2) }}
</div>
<div class="col-md-2">
{{ form_row(form.vars.prototype.cote) }}
</div>
<div class="col-md-2">
{{ form_row(form.vars.prototype.resultat) }}
</div>
</div>
<hr>
</div>
{% endblock %}
{% block body %}
{# {{ include('paris/_form.html.twig', {form:form, button: 'Ajouter'}) }} #}
<button type='button' id='btn-add' class='add_sport_link btn btn-primary'>Ajouter paris</button>
{{ form_start(form) }}
<div class="paris">
<div class="row">
<div class="col-md-4">
{{ form_row(form.mise) }}
</div>
<div class="col-md-4">
{{ form_row(form.type) }}
</div>
<div class="col-md-4">
{{ form_row(form.win) }}
</div>
</div>
<div class="col-md-4 matchs">
{% if form.rencontres|length > 0 %}
{% for index in 0..form.rencontres|length - 1 %}
{{ dump(index) }}
{{ form_row(form.rencontres[index]) }}
{% endfor %}
{% else %}
{{ form_row(form.rencontres) }}
{% endif %}
</div>
</div>
{{ form_end(form) }}
{% endblock %}
add (form.rencontres|length == 0):
enter image description here
edit (form.rencontres|length > 0):
enter image description here
Regards
PS: Sorry for my english
EDIT: My controller
#NicoHaase I dont think the problem is in the code.
I want just display my form template when I edit an object as when I add an object
`code
/**
* #Route("/paris/add", name="paris_add")
*/
public function add(Request $request)
{
$em = $this->getDoctrine()->getManager();
$paris = new paris();
$form = $this->createForm(ParisType::class, $paris);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($paris);
$em->flush();
return $this->redirectToRoute('paris');
}
return $this->render("paris/add.html.twig", [
'form' => $form->createView()
]);
}
/**
* #Route("/paris/{id}", name="paris_edit", requirements={"id":"\d+"})
* #param Paris $paris
* #param Request $request
*/
public function edit(Request $request, Paris $paris)
{
$form = $this->createForm(ParisType::class, $paris);
$form->handleRequest($request);
return $this->render("paris/add.html.twig", [
"paris" => $paris,
"form" => $form->createView(),
]);
}
`

New field not added to database when Customizing the registration form for FOSUserBundle

I am using FOSUserBundle and I am tring to Customizing the registration form by following this toturial:
https://symfonycasts.com/screencast/fosuserbundle/customize-forms
but I have an issue:
1- The new field "nom " is not visible in the database even after updating the database using :
php bin/console doctrine:schema:update --force
the result:
Nothing to update - your database is already in sync with the current entity metadata.
register_content.html.twig:
{% trans_default_domain 'FOSUserBundle' %}
<h1> </h1>
{{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register'), 'attr': {'class': 'fos_user_registration_register'}}) }}
<label class="col-xs-12 col-sm-12 col-md-12 col-lg-12 form-control-label " for="name" >Nom d'utilisateur <span class="required"></span>
</label>
<div class="col-xs-9 col-sm-9 col-md-9 col-lg-9">
{{ form_widget(form.username, {'attr': {'class' : 'form-control '}}) }}
</div>
<label class="col-xs-12 col-sm-12 col-md-12 col-lg-12 form-control-label " for="name" >E-mail <span class="required"></span>
</label>
<div class="col-xs-9 col-sm-9 col-md-9 col-lg-9">
{{ form_widget(form.email, {'attr': {'class' : 'form-control '}}) }}
</div>
<label class="col-xs-12 col-sm-12 col-md-12 col-lg-12 form-control-label " for="name" >Password <span class="required"></span>
</label>
<div class="col-xs-9 col-sm-9 col-md-9 col-lg-9">
{{ form_widget(form.plainPassword, {'attr': {'class' : 'form-control '}}) }}
</div>
<label class="col-xs-12 col-sm-12 col-md-12 col-lg-12 form-control-label " for="name" >Nom <span class="required"></span>
</label>
<div class="col-xs-9 col-sm-9 col-md-9 col-lg-9">
{{ form_widget(form.nom, {'attr': {'class' : 'form-control '}}) }}
</div>
<div>
<input class="btn btn-primary" type="submit" value="{{ 'registration.submit'|trans }}" />
</div>
{ form_end(form) }}
RegistrationFormType:
class RegistrationFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nom');
}
public function getParent()
{
return BaseRegistrationFormType::class;
}
public function getBlockPrefix()
{
return 'storeData.form.registration';
}
}
User.php
/**
* #ORM\Entity(repositoryClass="StoreDataBundle\Repository\UserRepository")
* #ORM\Table(name=" `user` ")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your name.", groups=
{"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max=255,
* minMessage="The name is too short.",
* maxMessage="The name is too long.",
* groups={"Registration", "Profile"}
* )*/
protected $nom;
/**
* #return mixed
*/
public function getNom()
{
return $this->nom;
}
/**
* #param mixed $nom
*/
public function setNom($nom)
{
$this->nom = $nom;
}
config.yml
fos_user:
db_driver: orm
firewall_name: main
user_class: StoreDataBundle\Entity\User
service: # this lines
mailer: fos_user.mailer.twig_swift # this lines
from_email:
address: "hello#aquanote.com"
sender_name: "AquaNote Postman"
registration:
form:
type: StoreDataBundle\Form\RegistrationFormType
service.yml
storeData.form.registration:
class: StoreDataBundle\Form\RegistrationFormType
tags:
- { name: form.type }
security.yml
security:
encoders:
StoreDataBundle\Entity\User: bcrypt
providers:
fos_userbundle:
id: fos_user.user_provider.username
firewalls:
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_token_generator: security.csrf.token_manager
anonymous: true
logout: true
remember_me:
secret: '%secret%'
UPDATE : User.orm.yml
StoreDataBundle\Entity\User:
type: entity
table: null
repositoryClass: StoreDataBundle\Repository\UserRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
lifecycleCallbacks: { }
Update:
I found my error: I had an yml file and annotation thats why it didn't work

how to override ProfileFormType to edit users? symfony2

I'm working with symfony2.I'm using FOSUserBundle, so i want to override FormType of edit user to add name to builder. so how i should do it?
what i've did :
ProfileFormType :
<?php
namespace UserBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use FOS\UserBundle\Form\Type\ProfileFormType as BaseType;
class ProfileFormType extends BaseType {
public function buildForm(FormBuilderInterface $builder, array $options) {
parent::buildForm($builder, $options);
// add your custom field
$builder->add('name')
->add('roles', 'collection', array(
'type' => 'choice',
'options' => array(
'choices' => array(
'ROLE_ADMIN' => 'Admin'))))
->add('image', new ImageType())
;
}
public function getName() {
return 'user_edit_profile';
}
}
services.yml
user.edit.form.type:
class: UserBundle\Form\Type\ProfileFormType
arguments: [%fos_user.model.user.class%]
tags:
- { name: form.type, alias: user_edit_profile }
edit.html.twig
{% extends "UserBundle::layout.html.twig" %}
{% block body %}
<center> <h1> Modification de profile </h1> </center>
<aside class="col-sm-3">
<div class="panel panel-default">
<div class="panel-heading">Modification</div>
<div class="panel-body">
Veuillez remplir les champs
</div>
</div>
</aside>
<!--timeline-->
<section class="timeline col-sm-9">
<!--post Timeline-->
<div class="thumbnail thumbnail-post">
<!--caption-->
<div class="caption">
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="form-horizontal">
<div class="form-group">
{{ form_errors(form.name) }}
<div class="col-sm-9">
Name {{ form_widget(form.name, { 'attr': {'class': 'form-control', 'placeholder': 'form.name'|trans } }) }}
</div>
</div>
<div class="form-group">
{{ form_errors(form.email) }}
<div class="col-sm-9">
Email {{ form_widget(form.email, { 'attr': {'class': 'form-control', 'placeholder': 'form.email'|trans } }) }}
</div>
</div>
<div class="form-group">
{{ form_errors(form.username) }}
<div class="col-sm-9">
Pseudo {{ form_widget(form.username, { 'attr': {'class': 'form-control', 'placeholder': 'form.username'|trans } }) }}
</div>
</div>
<div class="form-group">
{{ form_errors(form.current_password) }}
<div class="col-sm-9">
Mot de passe actuelle {{ form_widget(form.current_password, { 'attr': {'class': 'form-control', 'placeholder': 'form.current_password'|trans } }) }}
</div>
</div>
</br>
{{ form_rest(form) }}
<div class="form-group">
<div class="col-md-4 col-sm-4 col-xs-12 col-md-offset-3">
<input class="btn btn-default submit" type="submit" value="{{ 'registration.submit'|trans }}">
</div>
</div>
</form>
</div> <!--#caption-->
<!--#post timeline-->
</div>
<!--#timeline-->
</section>
{% endblock %}
{% block js %}
<script>
$(document).ready(function () {
$('#roles').hide();
});
</script>
{% endblock %}
i'm getting this error :
Neither the property "name" nor one of the methods "name()",
"getname()"/"isname()" or "__call()" exist and have public access in
class "Symfony\Component\Form\FormView" in
FOSUserBundle:Profile:edit.html.twig at line 28.
How can i resolve that.
profile:
form:
type: fos_user_profile
It needs that at config.yml of fos
Update your service file:
user.edit.form.type:
class: UserBundle\Form\Type\ProfileFormType
arguments: [%fos_user.model.user.class%]
decorates: fos_user.profile.form.type
tags:
- { name: form.type, alias: user_edit_profile }
fos_user.profile.form.type is mean our name of service which will be replace our service that name user.edit.form.type
Add use Symfony\Component\Form\FormBuilderInterface;
You got error:
Neither the property "name" nor one of the methods "name()", "getname()"/"isname()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView" in FOSUserBundle:Profile:edit.html.twig at line 28.
due to fos_user_user table has not name field. If you want to add field whitch not locate in table you'll should add field those fields in entity generate getters and setters and finaly create new migration and migrate up.

Symfony2 getLastUsername() function not working

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,

Resources