Search code examples
symfonydatefield

Date field type default only when no object is passed


I'm trying my hand at my first Symfony application, but as I'm working with forms, something a little counterintuitive is happening.

As you can see from my code, I have a date field that defaults to the current day. But when I pass an object to the form, this default overrides the object's current date.

I know this is how it is supposed to happen ('The default values for form fields are taken directly from the underlying data structure (e.g. an entity or an array). The data option overrides this default value.', from http://symfony.com/doc/current/reference/forms/types/date.html#data).

Is there any way to suppress this behaviour and only show the default if there is NO object passed?

$builder

  // other code

  ->add('date', 'date', array(
     'data' => new \DateTime()
  ))

 // other code

Solution

  • I would probably set it directly in my new Entity, not fixed in a form

    class YourClass 
    {
        private $date;
        //...
    
        public function __construct()
        {
            $this->date = new \DateTime;
        }
    }