I am doing a web application with symfony3 and I need a way to let the users to edit and update their profile. I used FosUserBundle to manage the the users access but i don't know what steps to take to solve my problem.
Does someone have some ideas or useful links to share ?
thank you
I Solved the problem. Yes it's my first question on stackoverflow and I'm learning.
here is my code:
dogController.php
/**
* #Route("/profile/edit", name= "edit_profile" )
*/
public function edit_profileAction(Request $request)
{
$user = $this->getUser();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isValid()) {
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
$event = new FormEvent($form, $request);
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
//$url = $this->generateUrl('fos_user_profile_show');
$url = $this->generateUrl('edit_profile');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
$this->get('session')->getFlashBag()->add(
'notice',
'Profile Updated!'
);
return $response;
}
return $this->render('dog/edit_profile.html.twig',array('form'=>$form->createView()));
}
UserType.php
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Vich\UploaderBundle\Form\Type\VichImageType;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Form\Extension\Core\Type\FileType;
class UserType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options){
$builder->add('username')
->add('name')
->add('surname')
->add('email')
->add('telephone')
->add('imageFile', FileType::Class );
}
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults( array('data_class' => 'AppBundle\Entity\User') );
}
public function getName() {
return 'appBundle_user';
}`enter code here`
}
edit_profile.html.twig
<header>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2 class="name">Edit Profile</h2>
<div class="row" >
<div class="col-lg-12">
<div class="input_width" >
{% for flashMessage in app.session.flashbag.get('notice') %}
<div class="alert alert-success alert">
{{ flashMessage }}
</div>
{% endfor %}
{{form_start(form, {'attr': {'class': 'form-horizontal'}} )}}
{{ form_errors(form) }}
<div class="form-group">
{{ form_label(form.username) }}
{{ form_errors(form.username) }}
{{ form_widget(form.username , {'attr': {'class': 'form-control'}} ) }}
</div>
<div class="form-group">
{{ form_label(form.email) }}
{{ form_errors(form.email) }}
{{ form_widget(form.email , {'attr': {'class': 'form-control'}} ) }}
</div>
<div class="form-group">
{{ form_label(form.name) }}
{{ form_errors(form.name) }}
{{ form_widget(form.name , {'attr': {'class': 'form-control'}} ) }}
</div>
<div class="form-group">
{{ form_label(form.surname) }}
{{ form_errors(form.surname) }}
{{ form_widget(form.surname, {'attr': {'class': 'form-control'}}) }}
</div>
<div class="form-group">
{{ form_label(form.telephone) }}
{{ form_errors(form.telephone) }}
{{ form_widget(form.telephone, {'attr': {'class': 'form-control'}}) }}
</div>
<div class="form-group">
{{ form_label(form.imageFile) }}
{{ form_errors(form.imageFile) }}
{{ form_widget(form.imageFile) }}
</div>
<input type="submit" value="Submit" class="btn btn-default bluInput " />
{{form_end(form)}}
</div>
</div>
</div>
</div>
</div>
</div>
</header>
Basically I had to create a form type class linked to my entity, then, use it in my controller as long as the Fos user bundle user manager.
Related
I work on my first symfony project and I need to create nice errors for a form with an uploading input.
Actually, I change with success my parameters to a limit post of 20Mo and a limit size for an uploaded file of 20Mo.
In my entity, I have an Assert (by symfony) on my property "portfolio".
/**
* #Assert\File(
* maxSize="5M",
* mimeTypes = {"application/pdf"},
* mimeTypesMessage = "Votre fichier doit être au format PDF"
* )
*/
public $portfolio;
Btw i made my import like asked in the symfony documentation.
I have the twig expression to display my errors directly when i try to validate a wrong form.
Here is my controller's function :
public function formjob(\Swift_Mailer $mailer, Request $request)
{
$job = new JobForm();
$form = $this->createFormBuilder($job)
->add("name", TextType::class, [
"label" => "Nom :"
])
->add("firstName", TextType::class, [
"label" => "Prénom :"
])
->add("mail", EmailType::class, [
"label" => "E-mail :"
])
->add("telephone", TelType::class, [
"label" => "Tel. ",
"required" => false,
"empty_data" => "Non Renseigné"
])
->add("url", UrlType::class, [
"label" => "Envoyez-nous l’adresse internet vers vos réalisations",
"required" => false,
])
->add("portfolio", FileType::class, [
"label" => "Envoyez votre portfolio au format PDF",
"required" => false,
"error_bubbling" => true
])
->add("envoyer", SubmitType::class)
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$attachment = $data->portfolio;
$mail = $data->mail;
if(isset($attachment) || isset($data->url)) {
$message = (new \Swift_Message())
->setSubject('Formulaire Job')
->setFrom($mail)
->setTo('nicolas.trinquet#laposte.net')
->setBody(
$this->renderView(
'mail/mailjob.html.twig', [
'data' => $data
]
),
'text/html'
);
if (isset($attachment)) {
$message->attach(\Swift_Attachment::fromPath($attachment)->setFilename('portfolio.pdf')->setContentType('application/pdf'));
}
$mailer->send($message);
return $this->redirectToRoute('sent');
}
}
return $this->render('main/formJob.html.twig', [
'form'=> $form->createView(),
]);
}
And here is my template :
{% extends 'layout.html.twig' %}{% block title %}Jobs{% endblock %}{% block stylesheets %}<link rel="stylesheet" type="text/css" href="formJobs.css"> {% endblock %}{% block body %}<div class="row">
<div class="col-lg-12">
<h1 class="antiqueO">Postuler</h1>
<h2 class="robotoR">Intitulé du poste</h2>
<h3 class="robotoM">Type de poste</h3>
<p class="robotoR">Description du poste</p>
<div class="trait_noir_separation"></div>
{{ form_start(form) }}
<div class="col-lg-12">
{{ form_label(form.name) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.name) }}
{{ form_widget(form.name) }}
</div>
<div class="col-lg-12">
{{ form_label(form.firstName) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.firstName) }}
{{ form_widget(form.firstName) }}
</div>
<div class="col-lg-12">
{{ form_label(form.mail) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.mail) }}
{{ form_widget(form.mail) }}
</div>
<div class="col-lg-12">
{{ form_label(form.telephone) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.telephone) }}
{{ form_widget(form.telephone) }}
</div>
<div class="col-lg-12">
{{ form_label(form.url) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.url) }}
{{ form_widget(form.url) }}
</div>
<div class="col-lg-12">
{{ form_label(form.portfolio) }}
</div>
<div class="col-lg-12">
{{ form_errors(form.portfolio) }}
{{ form_widget(form.portfolio, {'attr': {'class': 'form-control-file', 'accept' : 'application/pdf'}})}}
</div>
<div>
{{ form_widget(form.envoyer, {'attr': {'class': 'antiqueO send_button'}}) }}
</div>
{{ form_end(form) }}
</div>
</div>{% endblock body %}
Actually i have a problem : all my errors can be triggered and displayed.
BUT the error on my file input refuse to be displayed even if i have the error in my profiler toolbar :
Profiler Toolbar for size error
Profiler Toolbar for format error
What is the problem in my code? What is blocking my error display?
Based in https://symfony.com/doc/current/reference/forms/types/text.html#error-bubbling
error_bubbling
type: boolean default: false unless the form is compound
If true, any errors for this field will be passed to the parent field or form. For example, if set to true on a normal field, any errors for that field will be attached to the main form, not to the specific field.
So as you are using this attribute in portfilo property, the error is showing on
{{ form_errors(form) }}
and not in
{{ form_errors(form.portfolio) }}
Just try to remove error_bubbling from portfolio property in formjob function and the error should be showed in your form
I try editAction in symfony but I have error when if not change input file it update field file in database to null ... how to not update field file if not changed value in update action
code action:
/**
* #Route("/babysitter/update/{id}", name="update_babysitter_by_admin")
*
* #param Request $request
* #param BabySitter $babySitter
* #ParamConverter("id", options={"id": "id"})
*
* #return mixed
*/
public function updateBabySitterAction(BabySitter $babySitter, Request $request){
$em= $this->getDoctrine()->getManager();
$form= $this->createForm(BabySitterType::class, $babySitter,['requiredFile'=> false]);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
if($babySitter->getPicture()->getDocument()){
$this->uploadDocument->upload($babySitter->getPicture(), $this->getParameter('pictures_directory'));
}
if($babySitter->getCriminalRecord()->getDocument()){
$this->uploadDocument->upload($babySitter->getCriminalRecord(), $this->getParameter('criminalRecord_director_babySitter'));
}
if($babySitter->getIdCards()){
$this->uploadDocument->uploadIdCard($babySitter->getIdCards(), $babySitter,$this->getParameter('idCard_directory'));
}
$em->persist($babySitter);
$em->flush();
$url = $this->generateUrl('info_babySitter',['id'=> $babySitter->getId()]);
$response = new RedirectResponse($url);
return $response;
}
return $this->render('admin/registerBabySitter.html.twig',[
'form'=> $form->createView()
]);
}
code twig:
{% trans_default_domain 'FOSUserBundle' %}
<div class="register-box" style="width:460px">
<div class="register-box-body">
<p class="login-box-msg">Register a new BabySitter</p>
{{ form_start(form, {'method':'post', 'attr': {'class': 'fos_user_registration_register', 'novalidate': 'novalidate'}}) }}
<div class="form-group has-feedback">
{{ form_widget(form.email,{'attr': {'class': 'form-control', 'placeholder': 'Email'}}) }}
{{ form_errors(form.email) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.firstName,{'attr': {'class': 'form-control', 'placeholder': 'FirstName'}}) }}
{{ form_errors(form.firstName) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.lastName,{'attr': {'class': 'form-control', 'placeholder': 'LastName'}}) }}
{{ form_errors(form.lastName) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.plainPassword.first,{'attr': {'class': 'form-control', 'placeholder': 'Password'}}) }}
{{ form_errors(form.plainPassword.first) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.plainPassword.second,{'attr': {'class': 'form-control', 'placeholder': 'Repeat Password'}}) }}
{{ form_errors(form.plainPassword.second) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.genre,{'attr': {'class': 'form-control', 'placeholder': 'Genre'}}) }}
{{ form_errors(form.genre) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.dateBirth,{'attr': {'class': 'form-control', 'placeholder': 'date Birthday'}}) }}
{{ form_errors(form.dateBirth) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.linkVideo,{'attr': {'class': 'form-control', 'placeholder': 'link Video'}}) }}
{{ form_errors(form.linkVideo) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.criminalRecord) }}
{{ form_errors(form.criminalRecord) }}
</div>
<div class="form-group has-feedback">
<ul id="idCard-fields-list"
data-prototype="{{ form_widget(form.idCards.vars.prototype)|e }}"
data-widget-tags="{{ '<li></li>'|e }}">
{{ form_row(form.idCards) }}
{% for idCardField in form.idCards %}
<li>
{{ form_errors(idCardField) }}
{{ form_widget(idCardField) }}
</li>
{% endfor %}
</ul>
<div class="row">
<button type="button"
class="add-another-collection-widget-idCard btn btn-primary btn-flat"
data-list="#idCard-fields-list">Add another idCard</button>
</div>
</div>
<div class="form-group has-feedback">
{{ form_widget(form.nbrYears,{'attr': {'class': 'form-control', 'placeholder': 'Number Years'}}) }}
{{ form_errors(form.nbrYears) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.rib,{'attr': {'class': 'form-control', 'placeholder': ' rib'}}) }}
{{ form_errors(form.rib) }}
</div>
<div class="form-group has-feedback">
{{ form_widget(form.presentation,{'attr': {'class': 'form-control', 'placeholder': 'presentation'}}) }}
{{ form_errors(form.presentation) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.adress) }}
{{ form_errors(form.adress) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.availability) }}
{{ form_errors(form.availability) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.assignement) }}
{{ form_errors(form.assignement) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.qualification) }}
{{ form_errors(form.qualification) }}
</div>
<div class="form-group has-feedback">
{{ form_row(form.picture) }}
{{ form_errors(form.picture) }}
</div>
<div class="form-group has-feedback">
<ul id="language-fields-list"
data-prototype="{{ form_widget(form.languages.vars.prototype)|e }}"
data-widget-tags="{{ '<li></li>'|e }}">
{{ form_widget(form.languages) }}
{% for languageField in form.languages %}
<li>
{{ form_errors(languageField) }}
{{ form_widget(languageField) }}
</li>
{% endfor %}
</ul>
<div class="row">
<button type="button"
class="add-another-collection-widget btn btn-primary btn-flat"
data-list="#language-fields-list">Add another language</button>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<input type="submit" class="btn btn-primary btn-block btn-flat" value="{{ 'registration.submit'|trans }}">
</div>
<!-- /.col -->
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
</div>
<!-- /.form-box -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
jQuery(document).ready(function () {
jQuery('.add-another-collection-widget').click(function (e) {
var list = jQuery(jQuery(this).attr('data-list'));
// Try to find the counter of the list or use the length of the list
var counter = list.data('widget-counter') | list.children().length;
// grab the prototype template
var newWidget = list.attr('data-prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your emails
// end name attribute looks like name="contact[emails][2]"
newWidget = newWidget.replace(/__name__/g, counter);
// Increase the counter
counter++;
// And store it, the length cannot be used if deleting widgets is allowed
list.data('widget-counter', counter);
// create a new list element and add it to the list
var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
newElem.appendTo(list);
addTagFormDeleteLink(newElem);
});
function addTagFormDeleteLink($tagFormLi) {
var $removeFormButton = $('<button class="btn btn-danger btn-flat" style="margin-top:2%;margin-left:50%" type="button">Delete this Language</button>');
$tagFormLi.append($removeFormButton);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
jQuery('.add-another-collection-widget-idCard').click(function (e) {
var list = jQuery(jQuery(this).attr('data-list'));
// Try to find the counter of the list or use the length of the list
var counter = list.data('widget-counter') | list.children().length;
// grab the prototype template
var newWidget = list.attr('data-prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your emails
// end name attribute looks like name="contact[emails][2]"
newWidget = newWidget.replace(/__name__/g, counter);
// Increase the counter
counter++;
// And store it, the length cannot be used if deleting widgets is allowed
list.data('widget-counter', counter);
// create a new list element and add it to the list
var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
if(counter <= 3){ newElem.appendTo(list); }
});
function addIdCardFormDeleteLink($tagFormLi) {
var $removeFormButton = $('<button class="btn btn-danger btn-flat" style="margin-top:2%;margin-left:50%" type="button">Delete this idCard</button>');
$tagFormLi.append($removeFormButton);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
});
</script>
when i update entity and i not update field file i have field file in database null ... how to update entity without changed in input file
I am having a weird problem. I added an upload image field to a form. Every thing work fine when i use this code in the twig file
{{ form_start(form) }}
<button>d</button>
{{ form_end(form) }}
But when ever i want to use form_widget to costumize the look of the form this error appear when ever i try to sumit the form
FatalErrorException
Error: Call to a member function getFileName() on string.
This is the View that cause the problem
{% extends 'BridgeTravelBundle:Admin:layout.html.twig' %}
{% block body %}
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<form method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left">
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Nom</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{{ form_widget(form.name, { 'attr': {'class': 'form-control', 'placeholder': 'Prenom' } }) }}
{{ form_errors(form.name) }}
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Icon</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{{ form_widget(form.icon, { 'attr': {'class': 'form-control', 'placeholder': 'Prenom' } }) }}
{{ form_errors(form.icon) }}
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Icon</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{{ form_widget(form.file) }}
{{ form_errors(form.file) }}
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button class="btn btn-success">Valider</button>
</div>
</div>
</form>
</div>
</div>
{% endblock body %}
This is the Action that control the form.
public function addCategoryAction(Request $request){
$category=new Category();
$form=$this->createForm(CategoryType::class,$category);
$form->handleRequest($request);
if ($form->isSubmitted())
{
$image= $form['file']->getData();
$em=$this->getDoctrine()->getManager();
$req = $request->request->get('Bridge_TravelBundle_Category');
$category->setName($req['name']);
$category->setIcon($req['icon']);
$name = $req['name'];
try {
if(!is_dir("CategoriesPictures")){
mkdir("CategoriesPictures");
}
move_uploaded_file($image,"CategoriesPictures/".$image->getFileName());
rename("CategoriesPictures/".$image->getFileName() , "CategoriesPictures/".$name.".jpg");
}
catch (IOExceptionInterface $e) {
echo "Erreur Profil existant ou erreur upload image ".$e->getPath();
}
$em->persist($category);
$em->flush();
return $this->redirectToRoute('admin_categories');
}
return $this->render("BridgeTravelBundle:Admin:addcategory.html.twig",array('form' => $form->createView(),));
}
This the CategoryType.php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class CategoryType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name')
->add('icon')
->add('file',FileType::class, array(
'multiple' => false,
'attr' => array(
'accept' => 'image/*',
)
)
) ;
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bridge\TravelBundle\Entity\Category'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'Bridge_TravelBundle_Category';
}
}
This attribute enctype='multipart/form-data' is missing from your form tag.
You should just you form_start & form_end instead writing form tag by yourself.
You can also put custom attributes with form_start function like this
{{ form_start(form, { 'attr': {'class': 'foo', 'id': 'bar' } }) }}
Also, form_end is very important because it also print out form_rest and any missing field.
<form method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left">
will become
{{ form_start(form, { 'attr': { 'id': 'demo-form2', 'data-parsley-validate': null, 'class': 'form-horizontal form-label-left' } }) }}
and
</form>
will become
{{ form_end(form) }}
I have a form where user can submit a new Mandate. Every Mandate can have multiple Profiles linked to it.
Here is how the form looks like at this moment:
The Profiles field is added to the form like that (from MandateController):
$form = $this->createFormBuilder($mandate)
->add('content')
->add('name')
->add('company_name')
->add('budget')
->add('phone')
->add('email')
->add('description')
->add('profiles', EntityType::class, array(
'multiple' => true,
'expanded' => true,
'class' => 'KrownDashboardBundle:Profile',
'choice_label' => 'title',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('p')
->orderBy('p.title', 'ASC');
},
))
->getForm();
And the view is handled this way:
{{ form_start(form) }}
{{ form_errors(form) }}
<div>
<div class="col_full">
<label for="" class="control-label">{{ form_label(form.content) }}</label>
{{ form_widget(form.content, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.content) }}
</div>
<div class="col_full">
<label for="" class="control-label">Prénom et nom</label>
{{ form_widget(form.name, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.name) }}
</div>
<div class="col_full">
<label for="" class="control-label">Nom de lentreprise</label>
{{ form_widget(form.company_name, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.company_name) }}
</div>
<div class="col_full">
<label for="" class="control-label">Budget</label>
{{ form_widget(form.budget, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.budget) }}
</div>
<div class="col_full">
<label for="" class="control-label">Numéro de téléphone</label>
{{ form_widget(form.phone, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.phone) }}
</div>
<div class="col_full">
<label for="" class="control-label">E-mail</label>
{{ form_widget(form.email, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.email) }}
</div>
<div class="col_full">
<label for="" class="control-label">Description</label>
{{ form_widget(form.description, {'attr': {'class': 'form-control'}}) }}
{{ form_errors(form.description) }}
</div>
<div class="col_full">
<label for="" class="control-label">Profiles</label>
{{ form_widget(form.profiles) }}
{{ form_errors(form.profiles) }}
</div>
</div>
<button id="login-form-submit" class="button button-3d button-black nomargin" value="Log in" name="login-form-submit">Ok</button>
{{ form_end(form) }}
I want to modify the Profiles listing, so they look like this (all these fields are saved into the Profile entity):
Instead:
How can I achieve that? What's the best way to do it?
I've created a User class in my Bundle based on FOS\UserBundle\Model\User\BaseUser to register my users.
Here is my User.php :
class User extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// Constructor
public function __construct()
{
parent::__construct();
// your own logic
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
Here is my UserType.php :
class UserType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('valider', 'submit')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'CSW78\Bundle\Entity\User'
));
}
public function getParent()
{
return 'fos_user_registration';
}
/**
* #return string
*/
public function getName()
{
return 'user';
}
}
I overrode register.html.twig, putting it in /app/resources/FOSUserBundle/views/Registration and it is called.
Here is my register.html.twig :
{% block body %}
<div id="cadre" class="arrondi">
<h1>Inscription</h1>
<br>
{% block fos_user_content %}
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="fos_user_registration_register form-horizontal">
<div id="fos_user_registration_form">
<div class="form-group">
{{ form_label(form.username, 'Identifiant :', {'label_attr': {'class': 'col-xs-5 col-sm-4 col-md-3 col-lg-3 control-label'}}) }}
<div class="col-xs-7 col-sm-8 col-md-5 col-lg-5">
{{ form_widget(form.username, {'attr': {'class': 'form-control'}}) }}
</div>
</div>
<div class="form-group">
{{ form_label(form.email, 'Email :', {'label_attr': {'class': 'col-xs-5 col-sm-4 col-md-3 col-lg-3 control-label'}}) }}
<div class="col-xs-7 col-sm-8 col-md-5 col-lg-5">
{{ form_widget(form.email, {'attr': {'class': 'form-control'}}) }}
</div>
</div>
<div class="form-group">
{{ form_label(form.plainPassword.first, 'Mot de passe :', {'label_attr': {'class': 'col-xs-5 col-sm-4 col-md-3 col-lg-3 control-label'}}) }}
<div class="col-xs-7 col-sm-8 col-md-5 col-lg-5">
{{ form_widget(form.plainPassword.first, {'attr': {'class': 'form-control'}}) }}
</div>
</div>
<div class="form-group">
{{ form_label(form.plainPassword.second, 'Mot de passe (confirmation) :', {'label_attr': {'class': 'col-xs-5 col-sm-4 col-md-3 col-lg-3 control-label'}}) }}
<div class="col-xs-7 col-sm-8 col-md-5 col-lg-5">
{{ form_widget(form.plainPassword.second, {'attr': {'class': 'form-control'}}) }}
</div>
</div>
{{ form_widget(form._token, {'attr': {'class': 'form-control'}}) }}
{{ form_widget(form.valider, {'attr': {'class': 'btn btn-info btn-responsive btn-color'}}) }}
{{ form_end(form) }}
</div>
</form>
{% endblock %}
</div>
{% endblock %}
The problem is there is no validation made when I click on the submit button.
I thought that the validation constraints would inherit from the BaseUser validation constraints.
Is there something else to specify to call the BaseUser validation constraints on my User object ?
Another question: what if I want to customize the error messages, should I override the validation.xml file to do that ?
Thank you.
David