Symfony render required on TextField true - symfony

I don't understand why the rendering of this subform doesn't render the required tag on my TextType firstName;
My form in based on a Order entity
OrderFormType has a CollectionType of Tent, based on TentFormType
TentFormType has a CollectionType of Camper, based on CamperFormType
So Order > Tent > Camper
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
//...
class CamperFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('firstName', TextType::class, [
'required' => true, //Should even not been usefull since SF2.8
'label' => 'First name',
'attr' => [
'placeholder' => 'First name'
],
]);
//...
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\Camper',
'csrf_protection' => true,
'error_bubbling' => true,
'csrf_field_name' => '_token',
//...
]);
}
}
The fields are simply rendered with a form_widget:
{{ form_widget(form.firstName) }}
{{ form_widget(form.lastName) }}
But that not add the required field:
<input id="app_order_form_type_tents_0_campers_0_firstName" name="app_order_form_type[tents][0][campers][0][firstName]" placeholder="First name" class="form-control" type="text">
<input id="app_order_form_type_tents_0_campers_0_lastName" name="app_order_form_type[tents][0][campers][0][lastName]" placeholder="Last name" class="form-control" type="text">
I could do
{{ form_widget(form.firstName, {'attr': {'required': 'required'}}) }}
{{ form_widget(form.lastName, {'attr': {'required': 'required'}}) }}
But it shouldn't be required with my FormType...
Does anyone knows why ?
--EDIT--
My Camper Entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Camper.
*
* #ORM\Table(name="camper")
* #ORM\Entity()
*/
class Camper
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\NotBlank()
*
* #ORM\Column(name="firstName", type="string", length=255, nullable=false)
*/
private $firstName;
// ...
}

I'm sorry, i can not use comments so i put a suggestion here...
Try:
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

Related

Symfony, minMessage from Constraints not displaying

I'm new to Symfony and just making my first Project with the 3.4 version.
I have a problem when using Constraints on my form, I'm trying to make a field having some Length constraints, but as I test it with a short value that shouldn't be accepted, the form displays a default message in a speech bubble instead of the one I put in minMessage, and instead of displaying a message for maxLength, it just don't let me put more thant 20 characters in the field instead of displaying a message if there is more than 20. I'm not sure this is how it should work (???) and if it is can I manage error messages with another technic? I'm just putting constraints on a single field until I resolved this issue that's why the others one don't have any.
Here's the Controller Code :
<?php
namespace AppBundle\Controller;
use AppBundle\Form\UserType;
use AppBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
/**
* Class UserController
* #package AppBundle\Controller
* #Route("/user")
*/
class UserController extends Controller
{
/**
* #return \Symfony\Component\HttpFoundation\Response
* #Route("/add", name="add_user")
*/
public function addAction(Request $request)
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if($form->isSubmitted() && $form->isValid()){
$user->setPwd(md5($user->getPwd()));
$em->persist($user);
$em->flush();
return $this->render('#App/User/show.html.twig', array(
'user'=>$user
));
}
return $this->render('#App/User/add.html.twig', array(
'form'=>$form->createView()
));
}
}
UserType code:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
class UserType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('pseudo')
->add('nom')
->add('prenom')
->add('enseignant')
->add('pwd', PasswordType::class)
->add('confirm_pwd', PasswordType::class);
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\User'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_user';
}
}
User code (I'll just pute the code where my constraints are):
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class User
{
/**
* #var string
*
* #ORM\Column(name="pseudo", type="string", length=100, unique=true)
* #Assert\Length(
* min = 8,
* max = 20,
* minMessage = "Your first name must be at least {{ limit }} characters long",
* maxMessage = "Your first name cannot be longer than {{ limit }} characters"
* )
*/
private $pseudo;
}
And the twig page that I render:
{% extends 'base.html.twig' %}
{% block body %}
<h1 class="display-4">Formulaire d'inscription</h1>
{{ form_start(form) }}
{{ form_row(form.pseudo, {'label': 'Pseudo', 'attr':
{'placeholder': 'Pseudonyme ...'}}) }}
{{ form_row(form.nom, {'label': 'Nom', 'attr':
{'placeholder': 'Nom ...'}}) }}
{{ form_row(form.prenom, {'label': 'Prenom', 'attr':
{'placeholder': 'Prenom ...'}}) }}
{{ form_row(form.enseignant, {'label': 'Enseignant'}) }}
{{ form_row(form.pwd, {'label': 'Mot De Passe', 'attr':
{'placeholder': 'Mot De Passe'}}) }}
{{ form_row(form.confirm_pwd, {'label': 'Confirmation Mot De Passe', 'attr':
{'placeholder': 'Mot De Passe'}}) }}
<button type="submit" class="btn btn-success">Inscription </button>
{{ form_end(form) }}
{% endblock %}
Do you know what should I do to make it work?
I am sorry if my english is bad, and tell me if you need more or less code!
Have a nice day and thank you !
PS: I'm a real beginner with Symfony so be nice pls :)
PSbis: I already checked the documentation and I made everything that should have been made, but I could have missed something (even if I checked multiple times)
Edit: I added EqualTo and Unique constraints on other fields, and both error messages are displaying, so this is comming from the Length constraint and I really don't know why
You're forgetting to add form_errors. Check this out.

Symfony 4.2 VichUploaderBundle: File not saved

I'm using VichUploaderBundle in my application to upload the files.
Problem is that even if I followed the docs, the file isn't uploaded (even if seems to be all right, as profiles sais), and no rows was make in the entity table.
Here is my vich_uploader.yaml:
vich_uploader:
db_driver: orm
mappings:
media:
uri_prefix: /media
upload_destination: '%kernel.project_dir%/public/media'
inject_on_load: false
delete_on_update: true
delete_on_remove: true
Here is my Media Entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity
* #Vich\Uploadable
*/
class Media
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="media", fileNameProperty="imageName", size="imageSize")
*
* #var File
*/
private $imageFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
private $imageName;
/**
* #ORM\Column(type="integer")
*
* #var integer
*/
private $imageSize;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
private $updatedAt;
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $imageFile
*/
public function setImageFile(?File $imageFile = null): void
{
$this->imageFile = $imageFile;
if (null !== $imageFile) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
}
public function getImageFile(): ?File
{
return $this->imageFile;
}
public function setImageName(?string $imageName): void
{
$this->imageName = $imageName;
}
public function getImageName(): ?string
{
return $this->imageName;
}
public function setImageSize(?int $imageSize): void
{
$this->imageSize = $imageSize;
}
public function getImageSize(): ?int
{
return $this->imageSize;
}
}
I just need to store the file in the entity, there is no relations between files and other entities.
Here is my MediaType
<?php
namespace App\Form;
use App\Entity\Media;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichImageType;
class MediaType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('imageFile', VichImageType::class, [
'required' => false,
'allow_delete' => true,
'download_uri' => true
])
->add('submit', SubmitType::class, [
'attr' => [
'class' => 'btn btn-success'
],
'label' => 'Upload File'
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Media::class,
]);
}
}
The Form is handled by this Twig template:
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel">
<div class="panel-body">
{{ form_start(form) }}
{{ form_widget(form.imageFile) }}
</div>
<div class="panel-footer">
{{ form_widget(form.submit) }}
{{ form_end(form) }}
</div>
</div>
</div>
</div>
</div>

Symfony - Expected value of type Entity for association field got “string” instead

I have a UserEntity containing users email addresses and their password. Then a UserInstanceEntity that contains the users phone numbers as well as a ManyToOne relation on a PreferredContactEntity that allows the user to choose the contact method he prefers.
I wish when a user changes his profile that he can also modify his phone numbers and preferred method of contact. So in my controller I inserted UserType and UserInstanceType.
When I send the form, I get the error:
Expected value of type "App\Entity\PreferredContact" for association
field "App\Entity\UserInstance#$preferredContact", got "string"
instead.
UserEntity :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Validator\Constraints as AssertPerso;
use DateTime;
use DateTimeInterface;
/**
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
* #ORM\Table(name="app_user")
* #ORM\HasLifecycleCallbacks()
*/
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
* #AssertPerso\Email
*/
private $email;
/**
* #ORM\Column(type="array")
*/
private $roles = [];
/**
* #var string plain password
*/
private $plainPassword;
/**
* #ORM\Column(type="boolean")
*/
private $enabled;
/**
* #var string The hashed password
* #ORM\Column(type="string")
*/
private $password;
...
UserInstanceEntity :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\UserInstanceRepository")
* #ORM\Table(name="app_user_instance")
*/
class UserInstance
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $contactNumber;
/**
* #var string
*
* #ORM\Column(type="string", nullable=true)
*/
private $directContactNumber;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\PreferredContact")
* #ORM\JoinColumn(nullable=false)
*/
private $preferredContact;
PreferredContactEntity :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\PreferredContactRepository")
* #ORM\Table(name="app_user_preferred_contact")
*/
class PreferredContact
{
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string", length=180, unique=true)
*/
private $contact;
Table PreferredContact :
id contact
1 Mail
2 Phone
3 Webex Teams
UserController :
public function editProfil(Request $request): Response
{
$user = $this->getUser();
$userInstance = new UserInstance();
$form = $this->createForm(EditProfilType::class, $user);
$formUserInstance = $this->createForm(UserInstanceType::class, $userInstance);
$form->handleRequest($request);
$formUserInstance->handleRequest($request);
if ($form->isSubmitted() && $form->isValid() && $formUserInstance->isValid()) {
$this->getDoctrine()->getManager()->flush();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($userInstance);
$entityManager->flush();
$this->addFlash('success', 'Informations mises à jour avec succès !');
return $this->redirectToRoute('user_editprofil');
}
return $this->render($this->ticketingTemplates['edit_profil'], [
'user' => $user,
'form' => $form->createView(),
'formUserInstance' => $formUserInstance->createView(),
]);
}
UserType :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', null, array(
'label' => 'Email',
'required' => true)
)
->add('plainPassword',PasswordType::class, array(
'label' => 'Mot de passe',
'required' => true,
'constraints' => [
new Length([
'min' => 6,
'minMessage' => '{{ limit }} caractères minimum',
'max' => 4096,
]),
],
)
)
->add('roles', RolesType::class);
UserInstanceType :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('contactNumber', null, array(
'label' => 'Numéro de téléphone portable',
'required' => true,
))
->add('directContactNumber', null, array(
'label' => 'Numéro de ligne direct'), [
'required' => false,
'help' => 'Facultatif',
])
->add('preferredContact', EntityType::class, [
'class' => PreferredContact::class,
'label' => 'Méthode de contact préférée',
]);
editprofil.html.twig :
<form method="post" >
<fieldset>
<legend><i class="fa fa-lock" aria-hidden="true"></i> {{ 'Votre compte' }}</legend>
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_start(formUserInstance) }}
{{ form_widget(formUserInstance) }}
{{ form_end(formUserInstance) }}
<button type="submit" class="btn btn-primary">
<i class="fa fa-save" aria-hidden="true"></i> {{ 'Enregistrer' }}
</button>
<a href="{{ path('user_change_password') }}" class="btn btn-danger">
<i class="fa fa-lock" aria-hidden="true"></i> {{ 'Modifier le mot de passe' }}
</a>
{{ form_end(form) }}
</fieldset>
</form>
Do you know where this error comes from? Thank you
Edit :
EditProfilType :
class EditProfilType extends AbstractType
{
private $securityChecker;
private $token;
public function __construct(AuthorizationCheckerInterface $securityChecker, TokenStorageInterface $token)
{
$this->securityChecker = $securityChecker;
$this->token = $token;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', null, array(
'label' => 'Email ',
'required' => true
)
)
->add('firstName', null, array(
'label' => 'Prénom',
'required' => true)
)
->add('lastName', null, array(
'label' => 'Nom',
'required' => true)
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'data_class' => User::class,
]
);
}

My Symfony form errors are always global. Not linked to the specific field like supposed to

I have a Symfony form where I get errors when the fields are blanks.
I already try to set error_bubbling to false but it still not work (And is supposed to be false by default)
This is my code where I remove everything that is not necessary:
Controller:
/**
* #Route("/add", name="add")
*/
public function add(Request $request)
{
$post = new Post();
$form = $this->createForm(PostType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) { } else { }
return $this->render('blog/add.html.twig', array('form' => $form->createView()));
}
Entity:
/**
* #ORM\Entity(repositoryClass="App\Repository\PostRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Post
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
private $Title;
/**
* #ORM\Column(type="text")
* #Assert\NotBlank
*/
private $Content;
...
FormType:
namespace App\Form;
use App\Entity\Post;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title')
->add('content');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Post::class
]);
}
}
Form:
{% extends "base.html.twig" %}
{% block body %}
<h2>
Create a post
</h2>
{{ form_start(form) }}
{{ form_widget(form) }}
<input type="submit" class="btn" value="Create" />
{{ form_end(form) }}
{% endblock %}
When I look at the object after the post all the errors are linked to the form and there's no errors in the childs (The form fields).
Does anyone know what can be wrong?
In buildForm(), you need to capitalize your fields. They are case sensitive and they are capitalized in your database.

Handling dd/mm/yyyy format in symfon2/Doctrine

What should happen here is this:
Only dd/mm/yyyy format will be accepted for DOB.
If different format given then "The DoB field must have a valid format." message should read on the screen BUT this message should be coming from the ENTITY, not form TYPE set with 'invalid_message' attribute.
JFYI: I can define $dob as 'string' in the entity and as 'text' in the form type to make whole process work but it is not good practise. The reason is I don't want varchar field for $dob in database, I want date field.
PERSON ENTITY (Note: This is the only place I want form validation takes place):
namespace Se\HirBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Person
*
* #ORM\Entity
* #ORM\Table(name="person")
* #ORM\HasLifecycleCallbacks
*/
class Person
{
/**
* #var integer $id
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string $firstname
*
* #Assert\NotBlank(message = "The Firstname field should not be blank.")
* #Assert\Length(max = "100", maxMessage = "The Firstname field cannot be longer than {{ limit }} characters length.")
*
* #ORM\Column(type = "string", length = 100)
*/
protected $firstname;
/**
* #var date $dob
*
* #Assert\NotBlank(message = "The DoB field should not be blank.")
* #Assert\Regex(pattern = "/^(0[1-9]|[12][0-9]|3[01])[\/\-](0[1-9]|1[012])[\/\-]\d{4}$/", message = "The DoB field must have a valid format.")
*
* #ORM\Column(type = "date", length = 10)
*/
protected $dob;
/**
* #var datetime $created
*
* #ORM\Column(type="datetime")
*/
protected $created;
/**
* #var datetime $updated
*
* #ORM\Column(type="datetime", nullable = true)
*/
protected $updated;
/**
* Gets triggered only on insert
*
* #ORM\PrePersist
*/
public function onPrePersist()
{
$this->created = new \DateTime("now");
}
/**
* Gets triggered every time on update
*
* #ORM\PreUpdate
*/
public function onPreUpdate()
{
$this->updated = new \DateTime("now");
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set firstname
*
* #param string $firstname
* #return Person
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set dob
*
* #param string $dob
* #return Person
*/
public function setDob($dob)
{
$this->dob = $dob;
return $this;
}
/**
* Get dob
*
* #return string
*/
public function getDob()
{
return $this->dob;
}
}
Form TYPE file:
namespace Se\HirBundle\Form\Type\Person;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class CreateType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAction($options['action'])
->setMethod('POST')
->add('firstname', 'text',
array('label' => 'Firstname', 'error_bubbling' => true))
->add('dob', 'date',
array('label' => 'DoB', 'widget' => 'single_text',
'format' => 'dd/MM/yyyy', 'input' => 'datetime', 'error_bubbling' => true))
->add('create', 'submit',
array('label' => 'Create Person'));
}
public function getName()
{
return 'personcreate';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array('data_class' => 'Se\HirBundle\Entity\Person'));
}
}
CONTROLLER:
namespace Se\HirBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Se\HirBundle\Entity\Person;
use Se\HirBundle\Form\Type\Person\CreateType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class CrudController extends Controller
{
public function createAction()
{
$person = new Person();
$form = $this->createForm(new CreateType(), $person,
array('action' => $this->generateUrl('create_submit')));
return $this->render('SeHirBundle:Default:create.html.twig',
array('page' => 'Create', 'form' => $form->createView()));
}
public function createPersonAction(Request $request)
{
if ($request->getMethod() != 'POST')
{
return new Response('Only POST method is accepted');
}
$person = new Person();
$form = $this->createForm(new CreateType(), $person,
array('action' => $this->generateUrl('create_submit')));
$form->handleRequest($request);
if ($form->isValid())
{
$submission = $form->getData();
$em = $this->getDoctrine()->getManager();
$person = new Person();
$person->setFirstname($submission->getFirstname());
$person->setDob($submission->getDob());
$em->persist($person);
$em->flush();
$this->get('session')->getFlashBag()->add('message', 'Person successfully created!');
return $this->redirect($this->generateUrl('message'));
}
return $this->render('SeHirBundle:Default:create.html.twig',
array('page' => 'Create', 'form' => $form->createView()));
}
}
TWIG:
{% extends '::base.html.twig' %}
{% block title %}{{ page }}{% endblock %}
{% block body %}
<b>{{ page|upper }}</b>
<hr />
{{ form_start(form, {attr: {novalidate:'novalidate'}}) }}
{% if form_errors(form) != '' %}
<div>{{ form_errors(form) }}</div>
{% endif %}
<div>
{{ form_label(form.firstname) }}
{{ form_widget(form.firstname) }}
</div>
<div>
{{ form_label(form.dob) }}
{{ form_widget(form.dob, {'type':'text'}) }}
</div>
<br />
<div>
{{ form_widget(form.create) }}
</div>
{{ form_end(form)}}
{% endblock %}
Here is a solution based on the Symfony2 documentation:
Controller
Start of the file
use Symfony\Component\HttpFoundation\Response;
Function in the controller
This controller will display the dob field, since this is a Datetime object it requires to use format() in order to display it. This is just an example to show that Symfony2 recognizes the date and transform it internally.
Uncommenting the lines starting with // would be sufficient to persist the Person entity with the dob.
public function testAction(Request $request)
{
$person = new Person();
$form = $this->createFormBuilder($person)
->add('dob', 'date',
array(
'label' => 'DoB',
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'invalid_message' => 'Validation error goes here',
'error_bubbling' => true,
'input' => 'datetime' # return a Datetime object (*)
)
)
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
# perform some action, such as saving the task to the database
//$em = $this->getDoctrine()->getManager();
//$em->persist($person);
//$em->flush();
return new Response($person->getDob()->format('d-m-Y'));
}
return $this->render(
'YourBundle:Default:test.html.twig',
array(
'form' => $form->createView()
)
);
}
(*): http://symfony.com/fr/doc/master/reference/forms/types/date.html#input
Twig file
{{ form(form) }}
routing.yml
test:
pattern: /test/
defaults: { _controller: YourBundle:Default:test }
SOLUTION in Controller:
$dob = date('Y-m-d', strtotime(str_replace('/', '-', $submission->getDob())));
$person->setDob($dob);

Resources