Canser Yanbakan
Canser Yanbakan

Reputation: 3870

Symfony2 Form Builder PRE_SET_DATA Convert Datetime to String Date

I have a datetime field and i'm using jquery datepicker to select date with in a text field (input[type=text).

When i want to create a new record, there is no problem. When i want to edit that record, i have to set datetime data as text date format (Y-m-d) and print to text field.

My field (in orm.yml):

released_at:
  type: datetime
  nullable: true

My form builder:

$builder->add(
    'releasedAt',
        null,
        [
            'label' => 'Çıkış Tarihi',
            'mapped' => false, // false because setting the datetime data in the controller
            'attr' => ['class' => 'date-picker']
        ]
);

My form pre_set_data:

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        $form = $event->getForm();
        $game = $event->getData();

        if ($game instanceof Game) {
            $datetime = $game->getReleasedAt();
            $form->get('releasedAt')->setData(\Datetime::createFromFormat('Y-m-d', $datetime->format('Y-m-d')));
        } else {
            return;
        }
    });

Error:

The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class DateTime. You can avoid this error by setting the "data_class" option to "DateTime" or by adding a view transformer that transforms an instance of class DateTime to scalar, array or an instance of \ArrayAccess.

What is the problem here?

---- Edit ----

I have also tried this:

$builder->add(
        'releasedAt',
        'datetime',
        [
            'label' => 'Çıkış Tarihi',
            'date_widget' => 'single_text',
            'date_format'=>'y-M-d',
            'attr' => ['class' => 'date-picker']
        ]
    )

But the view is showing the time selections and wraps all fields with a div.

I don't want to edit datetime form view.

First option is better for me.

Thanks!

Upvotes: 0

Views: 1867

Answers (1)

Canser Yanbakan
Canser Yanbakan

Reputation: 3870

SOLUTION:

Solution is simple.

When we look at this diagram:

enter image description here

Just change the PRE_SET_DATA to POST_SET_DATA.

Code:

$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
    $form = $event->getForm();
    $game = $event->getData();

    if($game === null || $game->getId() === null)
        return;

    if ($game instanceof Game) {
        $datetime = $game->getReleasedAt();
        $form->get('releasedAt')->setData($game->getReleasedAt()->format('Y-m-d'));
    }
});

Upvotes: 0

Related Questions