Symfony API transforming date

498 Views Asked by At

I'm making an API with Symfony 4 and I'm trying to get it to accept a date, but it keeps throwing the Unable to transform data for property path "dateofbirth": Expected a string. error.

Field in entity:

/**
 * @ORM\Column(type="date", nullable=true)
 */
private $dateofbirth;

Field in Form:

->add('dateofbirth', DateType::class, [
    'html5' => false,
    'required' => false,
    'input' => 'string',
    'input_format' => 'Y-m-d'
])

Now if I send it JSON with "dateofbirth": "1990-02-12" for example, it throws that error. I've also tried sending something like "dateofbirth": "1990-02-12T00:00:00+01:00" with the 'input_format' set to Y-m-d\TH:i:sP, but I get the same issue.

I've been messing around with the options array for a while now and I've also tried configurations other than the one above, but that's what I have right now. Instead of listing all the ones I've tried that didn't work, I hope someone can just tell me what does.

1

There are 1 best solutions below

2
On BEST ANSWER

As per the DateType documentation:

input

The format of the input data - i.e. the format that the date is stored on your underlying object.

Since you have declared your entity as @Column(type="date") you should set input to datetime. Symfony will create the object according to the input_format and map it to the model.

And since you are sending a single field, set widget to single_text, as the default value of choice will expect an object with day, month, year.