Symfony: How to use Data Transformers with a FormFactory?

In my Symfony Application i have a From which contains a lot of checkboxes, radios, textfields and also DateTime Objects.
Everything but the DateTime Objects work fine, but with them i always get the error "Object of class DateTime could not be converted to string"
So i wanted to use this tutorial to change the datetime object to a string.


The thing is i am using a FormFactory and when i use the addModelTransformer()-Method like this…

1st Option:

$form->add($formFactory->createNamed('value', 'date', null, $fieldOptions));
$form->get('value')->addModelTransformer(new CallbackTransformer(
    function($dateAsDate){
        return $dateAsDate->format('Y-m-d');
    },
    function ($dateAsString){
        return "test"; //TODO: to be changed to make string to date
    }
));

…i get the Error "Call to undefined method SymfonyComponentFormForm::addModelTransformer() "


When i use the builder function outside the Formfactory like this…

2nd Option:

//$builder->addEventListener Stuff is above

$builder->get('value')->addModelTransformer(new CallbackTransformer(
   function($dateAsDate){ return $dateAsDate->format('Y-m-d'); },
   function ($dateAsString){ return 'null'; } //TODO: to be changed to make string to date
));

…i get the Error "The child with the name "value" does not exist."


Does anybody have an idea how to make this work?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *