我试图了解保存和检索DateTime字段的正确方法。 保存字段时,我必须传递一个DateTime对象,而不是像这样的字符串:
//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();
}
检索对象时,datetime字段作为DateTime对象返回,但createForm方法中的dataTransformer需要一个字符串..
//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);
}
表单构建器类
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';
}
}
答案 0 :(得分:1)
在表单构建器中向字段添加类型:
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';
}
}