Symfony Rest Json Datetime

The problem

I was making some improvements to the PlanIT project that I'm redesigning all the source code to work with AngularJS and Symfony.

In the project I have some date time forms parameters that are sent in JSON like this :

{"user":1,"name":"Test project #3","description":"Test project #3","begin":"2012-12-12 10:00:00","end":"2013-12-12 10:00:00"}

I wanted to use Symfony form validation to valid my fields and save the entity to database. I used the FOS Rest Bundle in my project to get the form parameters this way :

$project["name"] = $request->request->get('name');
$project["description"] = $request->request->get('description');
$project["begin"] = $request->request->get('begin');
$project["end"] = $request->request->get('end');


if ($form->isValid()) {
    // Save entity

The problem I had is that the Datetime parameters was just ignored and transformed to null values.

The solution

After some researches online, I found that you need to generate the bound datetime form value in a different manner : the object should have defined the year, month, day, hour, minute and seconds separately in order to be bound successfully. So there is the solution I opted for :

$project["name"] = $request->request->get('name');
$project["description"] = $request->request->get('description');

$tmpDatetime = new \DateTime($request->request->get('begin'));
$project["begin"] = array();
$project["begin"]["year"] = $tmpDatetime->format('Y');
$project["begin"]["month"] = $tmpDatetime->format('m');
$project["begin"]["day"] = $tmpDatetime->format('d');
$project["begin"]["hour"] = $tmpDatetime->format('H');
$project["begin"]["minute"] = $tmpDatetime->format('i');
$project["begin"]["second"] = $tmpDatetime->format('s');

$tmpDatetime = new \DateTime($request->request->get('end'));
$project["end"] = array();
$project["end"]["year"] = $tmpDatetime->format('Y');
$project["end"]["month"] = $tmpDatetime->format('m');
$project["end"]["day"] = $tmpDatetime->format('d');
$project["end"]["hour"] = $tmpDatetime->format('H');
$project["end"]["minute"] = $tmpDatetime->format('i');
$project["end"]["second"] = $tmpDatetime->format('s');


if ($form->isValid()) {
    // Save Entity

I hope that this will help you to bind date and datetime base JSON parameters to your Symfony form.


Most seen