You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
feature symfony#50295 [PropertyAccess] Auto-cast from/to DateTime/Immutable when appropriate (nicolas-grekas)
This PR was merged into the 6.4 branch.
Discussion
----------
[PropertyAccess] Auto-cast from/to DateTime/Immutable when appropriate
| Q | A
| ------------- | ---
| Branch? | 6.4
| Bug fix? | no
| New feature? | yes
| Deprecations? | no
| Tickets | -
| License | MIT
| Doc PR | -
Best reviewed [ignoring whitespaces](https://github.com/symfony/symfony/pull/50295/files?w=1).
My starting point is a form with a date defined as such:
```php
class MyFormType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('some_date', DateTimeType::class)
;
}
// ...
}
class MyEntity
{
private ?\DateTimeImmutable $someDate = null;
//...
}
```
Then doing something like:
```php
$myEntity = new MyEntity();
$form = $this->createForm(MyFormType::class, $myEntity);
```
If I submit this form, I get:
```
Expected argument of type "DateTimeImmutable", "DateTime" given at property path "some_date".
```
The current solution is to set option `input` to `datetime_immutable` in `buildForm()`.
But this is boring. Too much boilerplate.
I've tried looking at the Form component to define the `input` option based on the entity provided when building the form, but this entity is not passed to sub-forms, so that we have no way to do this.
The only way I found is the one attached: if we cannot set a `DateTime`, we try setting a `DateTimeImmutable`.
I thought about changing the default value of option `input` to `datetime_immutable`, but this would need a nasty deprecation that'd force everybody to write even more boilerplate before v7, while what we want is less.
So here we are.
Commits
-------
3156a60 [PropertyAccess] Auto-cast from/to DateTime/Immutable when appropriate
thrownewNoSuchPropertyException(sprintf('Cannot write property "%s" to an array. Maybe you should write the property path as "[%1$s]" instead?', $property));
@@ -524,24 +524,37 @@ private function writeProperty(array $zval, string $property, mixed $value): voi
0 commit comments