Symfony2: How to set default value for a field DateTime

Refresh

November 2018

Views

1k time

4

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 answers

0

Другой вариант:

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

Вы должны заменить:

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

от

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