Custom object type is hidden without passing the class always
I am currently using a custom type in some forms, mostly becomes "id to entity" and "entity to id" thanks to bjo3rnf , but I don't want to go through every time class
, but for laziness and other problems.
I know that if I add a field to the FormBuilder and pass null in the symfony type, guess the correct type, I think it is using the property of the data_class
main form, I want to do the same to guess the correct class, but I donβt know how to get access to parentdata_class
@ jamek's answer works in some cases where others fail
Example:
use Doctrine\ORM\Mapping as ORM;
class Person {
/**
* @var int
* @ORM\Id()
* @ORM\GeneratedValue(strategy="IDENTITY")
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @var string
* @ORM\Column(length=150, type="string")
*/
protected $name;
/**
* @var City
* @ORM\ManyToOne(targetEntity="City")
*/
protected $city;
}
class City {
/**
* @var int
* @ORM\Id()
* @ORM\GeneratedValue(strategy="IDENTITY")
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @var string
* @ORM\Column(length=150, type="string")
*/
protected $name;
}
in controller when i want to create a new object
$object = new Person();
$form = $formFactory->create(new PersonType(), $object);
$form->submit($request); // here fails because cant convert city_id to City object
only works for existing object
$object = $manager->find('Person', $id);
$form = $formFactory->create(new PersonType(), $object);
$form->submit($request); // here works fine property is a object and the code get_class($builder->getData()) get the correct City class
source to share
If I understand that you want u to change in the buildForm method:
$transformer = new EntityToIdTransformer($this->objectManager, $options['class']);
to
$transformer = new EntityToIdTransformer($this->objectManager, get_class($builder->getData()));
And remove required from Option resolver for class
source to share
You can add to the construct in the Person class
class Person { ... public function __construct() { $this->city = new City(); } }
source to share