symfony - Handling dd/mm/yyyy format in symfon2/Doctrine -


what should happen here this:

  • only dd/mm/yyyy format accepted dob.
  • if different format given "the dob field must have valid format." message should read on screen but message should coming entity, not form type set 'invalid_message' attribute.

jfyi: can define $dob 'string' in entity , 'text' in form type make whole process work not practise. reason don't want varchar field $dob in database, want date field.

person entity (note: place want form validation takes place):

namespace se\hirbundle\entity;  use symfony\component\validator\constraints assert; use doctrine\orm\mapping 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 blank.")      * @assert\length(max = "100", maxmessage = "the firstname field cannot longer {{ limit }} characters length.")      *       * @orm\column(type = "string", length = 100)      */     protected $firstname;      /**      * @var date $dob      *       * @assert\notblank(message = "the dob field should not 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 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 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");     }         /**      * 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;     }      /**      * 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;     }      /**      * 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 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 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 solution based on symfony2 documentation:

controller

start of file

use symfony\component\httpfoundation\response; 

function in controller

this controller display dob field, since datetime object requires use format() in order display it. example show symfony2 recognizes date , transform internally.

uncommenting lines starting // sufficient persist person entity 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 datetime object (*)             )         )         ->getform();      $form->handlerequest($request);      if ($form->isvalid()) {         # perform action, such saving task 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 } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -