Skip to content
Advertisement

Symfony TimeType set default value without duplicate value or overwrite

Im trying to make a user friendly timepicker. I use symfony 4.4 together with the form builder to create this timepicker. I use this timepicker when im creating my entity and editing my entity. Now I run into a small issue… I want the time to be at a specific “default” value. So I did the following.

$builder
    ->add('start_time', TimeType::class, [
        // Make sure I only see one of those values.
        'minutes' => [0, 15, 30, 45],
        // Always sets it to 7:30 even when im editing...
        'data' => new DateTime('07:30')
    ])
    ->add('end_time', TimeType::class, [
        'minutes' => [0, 15, 30, 45],
        // Kinda works but it shows a duplicate value when selecting a value.
        'placeholder' => [
            'hour' => '16',
            'minute' => '30'
        ]
    ])
    ;
}

The ‘data’ object does not work because when I use this form in editing my entity it overwrites the saved data from the database. Symfony also explained this in there documentation:

The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overridden when the form edits an already persisted object, causing it to lose its persisted value when the form is submitted.

The ‘placeholder’ object does fix this problem but shows a duplicate value in the select field as shown below:

enter image description here

I just want the default value without duplicate values or override rules when editing.

Possible solution: I could use the ‘data’ object for just the create entity part. Then create a new entityType class with a copy of the builder but now without the ‘data’ class so it loads the time from the database. This new class I would use for the edit entity part. Sad part here is that it is a ugly fix since I copy a whole class just for a default value.

Advertisement

Answer

You can set directly in your entity/model the “time” that you want, for example in your “new controller action” $myEntity->setTime(...) and let Symfony and Doctrine do their jobs in your “edit controller action”.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement