4
votes

I work with Symfony 2.8

I have a table named: "Docentes" with a DateTime field "fechaAlta"

I need the default value of this field is "today" when I add a new record

I generate CRUD, using command generate:doctrine:crud

In the file "DocentesController.php" Symfony create two function: "newAction" and "editAction" (among other). Both using the same Form, insert in the file "DocentesType.php" in the folder "Form":

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder

        ->add('fechaAlta', 'date')
        ->add('dni')
        #
    ;
}

I tried two solutions:

ONE: In the Entity file named, "Docentes.php" I add the function:

  public function  __construct()
{
$this->fechaAlta = new \DateTime();    
}

But when I use the form to add the new record, the field "fechaAlta" is displayed with the values​​: Day 01, Month 01 and Year 2011. Not with the current date.

TWO:

I edit the function buildForm:

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

Now, when I add a new record, I obtain again the values: Day 01, Month 01 and Year 2011 but when I edit a record, Symfony change my original value, for example 2016-03-25 and set the today value! All the opposite of what I need!

2
When I change: '->add('fechaAlta', 'date', array( 'data' => new \DateTime()))' to '->add('fechaAlta', 'date', array( 'data' => new \DateTime('now')))' I obtain the date today in case a new record, but remains the problem when I edit a record. - Jorge H
Are you 100% certain your date/time/timezone settings on your server & php.ini are correct? Anyway, you could call $entity->setFetchAlta(new \DateTime()); in the newAction I'd guess? - ccKep

2 Answers

0
votes

You should replace :

public function  __construct()
{
$this->fechaAlta = new \DateTime();    
}

by

public function  __construct()
{
$this->fechaAlta = new \DateTime('now');    
}
0
votes

Another option:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('fechaAlta', 'date', array(
            'empty_data' => new \DateTime('now'),
        ))
        ->add('dni')
    ;
}