Reputation: 305
Is it possible to build a form from 2 joined entity objects?
I have two entities property
& propertylanguage
which are joined on onetomany relation.
(One property can have many languages)
Language has a title
and description
colomns.
So one property can have a english, french, german title.
I am trying to build a form out of that. See below.
Controller: addProperty.php
class AddPropertyController extends Controller
{
// ....
public function indexAction(Request $request)
{
$property = new property;
$language = new propertyLanguage;
$property ->addpropertylanguage($language);
$form = $this->createForm(new propertyType($this->getDoctrine()),$property);
// .....
}
Form type: propertType.php
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('title', 'text');
// other ->add() below.
}
It returns the following error:
Neither property "title" nor method "getTitle()" nor method "isTitle()" exists in class "\defaultBundle\Entity\property"
Of course there is no property Title in property, but there is one in propertylanguage.. Even if I try: ->add('title', 'entity', array('class'=>defaultBundle:propertylanguage)); it doesn't work.
Thanks if you have time to help me.
Best,
Pierre.
Upvotes: 3
Views: 2266
Reputation: 48893
What you will want to do is make a PropertyLanguageType class as well as a PropertyType.
Then, in your PropertyType you will embed the PropertyLanguageType:
public function buildForm(FormBuilder $builder, array $options)
{
// $builder->add('propertyLanguage', new PropertyLanguageType());
// Since we have a 1 to many relation, then a collection is needed
$builder->add('propertyLanguage', 'collection', array('type' => new PropertyLanguageType()));
The PropertyLanguageType is where you add the title.
It's all in the forms section in the manual but it might take several readings.
A second approach is to add a getTitle to your Property entity which would return the title from the PropertyLanguage entity. By doing this, your original form will work. But it can be a bit of a mess when you start to have multiple associations with multiple attributes. Best to just define a type for each entity.
Upvotes: 1
Reputation: 901
You could use a query_builder when defining the form. Here's how your form class might look like. Of course it will certainly not be exactly as so but that will give you a good start ;)
public function __construct($id)
{
$this->propertylanguageId = $id;
}
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('propertylanguage', 'entity', array(
'label' => 'Property Language',
'class' => 'YourAdressToBundle:Propertylanguage',
'query_builder' => function(EntityRepository $er) use ($propertylanguageId) {
return $er->createQueryBuilder('p')
->join('p.property', 'prop', Expr\Join::WITH, 'prop.id = :propertylanguageId')
->setParameter('propertylanguageId', $propertylanguageId);
},
));
}
Hope that'll be helpful
Upvotes: 0