Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony persist datetime from json data

Hello I recive data as JSON format and on my server site i have to store them via Doctrine. Everything gone fine but I have validation error when i recive datetime format data. I test this case on separated action in controller:

public function indexAction($name)
{

    $em = $this->getDoctrine()->getManager();

    $test = new Test();
    $test->setName("Test");
    //$test->setStart(new \DateTime());
    $form = $this->createForm(new TestType(), $test);

    $store = array(
        "name" => "Test",
        "start" => new \DateTime()//will be something like *2014-04-09 11:11:11'
    );

    $form->submit($store);

    if ($form->isValid()) {
        $em->persist($test);
        $em->flush();
    } else var_dump($this->getErrorMessages($form));


    return $this->render('CodeTestBundle:Default:index.html.twig', array('name' => $name));
}

var dump is:

array (size=1) 'start' => array (size=3) 0 => string 'This value is not valid.' (length=24)

  'date' => 
    array (size=3)
      'year' => 
        array (size=0)
          ...
      'month' => 
        array (size=0)
          ...
      'day' => 
        array (size=0)
          ...
  'time' => 
    array (size=2)
      'hour' => 
        array (size=0)
          ...
      'minute' => 
        array (size=0)
          ...
like image 801
strz Avatar asked Aug 22 '26 09:08

strz


2 Answers

Your problem is that the form framework expects the view data to be handled by one widget for each of the date and time components because the default widget setting of the datetime field type is choice.

If you configure your datetime field to be a single text input, your validator receives one string instead of an array structure and handles it as you expect it to without doing any additional transformation. In your case the field configuration would look like:

$builder->add('start', 'datetime', array(
    'widget' => 'single_text',
    'input' => 'datetime'
));
like image 97
cfo Avatar answered Aug 24 '26 22:08

cfo


Hum, you should use instead handleRequest :

public function indexAction($name, Request $request) // Add the Request
{

    $em = $this->getDoctrine()->getManager();

    $test = new Test();
    $test->setName("Test");
    //$test->setStart(new \DateTime());
    $form = $this->createForm(new TestType(), $test);

    $store = array(
        "name" => "Test",
        "start" => new \DateTime()//will be something like *2014-04-09 11:11:11'
    );

    // $form->submit($store);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em->persist($test);
        $em->flush();
    } else var_dump($this->getErrorMessages($form));


    return $this->render('CodeTestBundle:Default:index.html.twig', array('name' => $name));
}
like image 23
Michael Villeneuve Avatar answered Aug 24 '26 23:08

Michael Villeneuve