Reputation: 350
I would like to create a html choice field with datetime entries of the last edits made. When taking any other fields in the database this works, with datetime it doesn't.
In the formtype I have
class MemberlistType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('CreatedAt', 'entity', array(
'mapped' => false,
'class' => 'TestProject\TestBundle\Entity\Memberlist',
'property' => 'created_at'
))
`
In the view I have
{{form_label(form.children.memberlists[0].children.CreatedAt}}
{{form_widget(form.children.memberlists[0].children.CreatedAt}}
{{form_errors(form.children.memberlists[0].children.CreatedAt)}}
And I get:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object
of class DateTime could not be converted to string in /var/www/symfony/vendor/symfony/symfony
/src/Symfony/Component/Translation/Translator.php line 188") in
TestprojectTestBundle:Default:updateData.html.twig at line 77
How can I convert this datetime to string in an easy way?
Upvotes: 2
Views: 2496
Reputation: 1847
You could call the twig filter "date":
{{form_label(form.children.memberlists[0].children.CreatedAt|date("m/d/Y")}}
{{form_widget(form.children.memberlists[0].children.CreatedAt|date("m/d/Y")}}
{{form_errors(form.children.memberlists[0].children.CreatedAt|date("m/d/Y"))}}
Edit, i misread the question... Like ZhukV said, you need a ViewTransformer:
namespace My\Bundle\Form\Transformers;
class DateToStringTransformer
{
public function transform($dateObj)
{
if (null === $dateObj) {
return "";
}
return $dateObj->format('m/d/Y');
}
public function reverseTransform($date)
{
if ($date === "") {
return null;
}
$dateObj = new \DateTime($issue);
return $dateObj;
}
}
then call it in your form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new new DateToStringTransformer();
$builder
->add(
$builder->create('CreatedAt', 'entity', array(
'mapped' => false,
'class' => 'TestProject\TestBundle\Entity\Memberlist',
'property' => 'created_at'
))->addViewTransformer($transformer)
)
More info here: http://symfony.com/fr/doc/current/cookbook/form/data_transformers.html
Upvotes: 1
Reputation: 3188
You have this error because entity try view name as string, but object \DateTime not have __toString method.
Best solution - create custom view transformer.
Upvotes: 1