1

I am trying to understand the proper way for saving and retrieving a DateTime field. When saving the field I have to pass a DateTime object not string like this:

//Store a product
public function storeAction(Request $request) {
    $product = new Product();
    $createdAt = $request->request->get('createdAt');
    if (empty($createdAt)) {
        $product->setCreatedAt(null);
    } else {
        $product->setCreatedAt(new \DateTime($createdAt));
    }
    $em = $this->getDoctrine()->getManager();
    $em->persist($product);
    $em->flush();        
}

When retrieving the object the datetime field is returned as a DateTime object but the dataTransformer in the createForm method expects a string..

//Show a product   
public function showAction()
{    
    $product = $this->getDoctrine()
        ->getRepository('AcmeStoreBundle:Product')
        ->find($id);
    //TransformationFailedException in DateTimeToStringTransformer.php line 138 
    $form = $this->createForm(new ProductType(), $product); 
}

The Form builder class

class ProductType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('createdAt');
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => '\Acme\ProductBundle\Entity\Product',
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'acme_productbundle_product';
    }
}

1 Answer 1

1

Add a type to your field in your form builder :

class ProductType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('createdAt', 'datetime');
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => '\Acme\ProductBundle\Entity\Product',
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'acme_productbundle_product';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.