Skip to content

[Form] DateIntervalType: Unable to transform value for property path "[weeks]": Expected a string. #27378

@krixon

Description

@krixon

Symfony version(s) affected: 3.2 and later

Description
When using the DateIntervalType form type with the integer widget and using weeks rather than days, the following exception is thrown when rendering an interval containing exactly 0 weeks:

Unable to transform value for property path "[weeks]": Expected a string.

The exception is thrown in \Symfony\Component\Form\Extension\Core\DataTransformer\NumberToLocalizedStringTransformer, line 142.

The problem is that \Symfony\Component\Form\Extension\Core\DataTransformer\DateIntervalToArrayTransformer initialises the value for the weeks part of the interval to integer 0. If days is available, this will be updated to a numeric string, but if not it remains at integer 0.

if (in_array('weeks', $this->fields, true)) {
    $result['weeks'] = 0;
    if (isset($result['days']) && (int) $result['days'] >= 7) {
        $result['weeks'] = (string) floor($result['days'] / 7);
        $result['days'] = (string) ($result['days'] % 7);
    }
}

Ultimately this integer reaches NumberToLocalizedStringTransformer, where on line 141 a type check occurs:

if (!is_string($value)) {
    throw new TransformationFailedException('Expected a string.');
}

How to reproduce
Create a form with the following DateIntervalType child:

$builder->add('interval', DateIntervalType::class, [
    'widget'     => 'integer',
    'with_weeks' => true,
    'with_days'  => false,
]);

Set the form's data to new \DateInteval('PY1M1W0'). Render the form to produce the error.

Possible Solution
Change the default value for weeks to '0'. PR incoming shortly.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions