-1

In a Symfony Form I have:

->add('fechalimite', DateType::class, [
  'format' => 'dMMMMyyyy',
  'data' => new \DateTime(),
])

Opening the form, I have in fechalimite field today's date: 15 December 2018. I can change the field, ex. 28 December 2018, and I submit the change in database without problem.

The problem come editing the form. When I edit the field take today's date, not 28 December 2018.

I am looking for a data default that does not remain in edit mode.

How can solve it?

M. Galardi
  • 130
  • 2
  • 13
  • Data option always overrides data of underlying object, so you should not use it. – u_mulder Dec 15 '18 at 20:14
  • Possible duplicate of [Set default value on Datetime field in symfony2 form](https://stackoverflow.com/questions/8713200/set-default-value-on-datetime-field-in-symfony2-form) – u_mulder Dec 15 '18 at 20:18
  • Hi u_mulder, thanks for your answer. Then, is it possible to condition the ->add() of the form depending on whether the path is edit or create? which would be an alternative and possible solution to what I'm looking for. – M. Galardi Dec 15 '18 at 20:55
  • U_mulder, in "Set default value on Datetime field in symfony2 form" there is a syntax problem. It has nothing to do with my question – M. Galardi Dec 15 '18 at 21:28

2 Answers2

1

You can use your entity constructor to set the default value like this:

class YourEntity {
  private $fechalimite;

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

That will set the default value when you create a new entity.

  • Thanks Rodmar, I try your solution and works fine too, and It's more elegant than mine for what I'm looking for. – M. Galardi Dec 16 '18 at 13:51
0

I have found the solution to discriminate between create and edit:

$formMapper;

    if ($this->isCurrentRoute('create')) {
    $formMapper
        ->add('fechalimite', DateType::class, [
          'format' => 'dMMMMyyyy',
          'data' => new \DateTime(),
        ])
        ;
    } else {
    $formMapper
        ->add('fechalimite', DateType::class, [
          'format' => 'dMMMMyyyy',
        ])
        ;
    }
M. Galardi
  • 130
  • 2
  • 13