问题
I am using Symfony 2.1.3-DEV and trying to accomplish transforming entity to string (ID of some kind) and then back from string to entity when form is submitted. The issue is the same if I'm using the transformer given in the cookbook: http://symfony.com/doc/master/cookbook/form/data_transformers.html
Controller code:
$task = $entityManager->find('AcmeTaskBundle:Task', $id);
$form = $this->createForm(new TaskType(), $task); // so $task->issue is Issue object
I get this error:
The form's view data is expected to be an instance of class Acme\TaskBundle\Entity\Issue, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of Acme\TaskBundle\Entity\Issue.
The thing is, that I already have a transformer, which transforms TO string.
From the Form.php
:
if (null !== $dataClass && !$viewData instanceof $dataClass) {
throw new FormException(
//...
);
}
Why $viewData
is checked to be instance of data_class
parameter (or the guessed type of given object)? Isn't view data supposed to be string/array etc.? Am I missing something?
回答1:
After some digging step-by-step I found the problem that I was facing.
View data indeed must be the instance of class specified by data_class
parameter. If you are using transformer Object -> string, you must set the data_class
parameter to null
.
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => null,
));
}
By default, data_class
is result of get_class
of specified initial data. If you pass object to controller's createForm
or some corresponding form-creator function, and no default value for data_class
exists, it will be set to class of given object.
Still, the example given in the docs works fine - if form is inner (inside another form), data_class
will not be set so it will be null
.
As it's very rare to make form only from one field (text field in my transformer case), usually this form with transformer will be inside some other form, so it'll work fine.
回答2:
I had the same problem because I accidentally typed in my controller:
$em->getRepository('AcmeWhateverBundle:Something')->findBy(array('id' => $id), array());
instead of:
$em->getRepository('AcmeWhateverBundle:Something')->findOneBy(array('id' => $id), array());
So If you're not using any custom data transformers check that $entity in the following line is an object of the same class defined as data_class in your FormType:
Scope Controller:
$form = $this->createForm(new SomethingType(), $entity, array( ....
来源:https://stackoverflow.com/questions/13782878/symfony2-form-entity-to-string-transformer-issue