I would like to know with the following code, how to display in the generated form, a set of Contacts, linked to the Company of this note, instead of all contacts in the DB?
Entity Note :
/**
* @ORM\ManyToOne(targetEntity="Main\MainBundle\Entity\NoteType")
* @ORM\JoinColumn(nullable=false)
*/
private $noteType;
/**
* @ORM\ManyToOne(targetEntity="Main\MainBundle\Entity\Contact", inversedBy="contacts")
* @ORM\JoinColumn(nullable=true)
*/
private $contact;
/**
* @ORM\ManyToOne(targetEntity="Main\MainBundle\Entity\Company")
* @ORM\JoinColumn(nullable=false)
*/
private $company;
/**
* @ORM\ManyToOne(targetEntity="Main\MainBundle\Entity\User", inversedBy="users")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
Entity Company :
/**
* @ORM\OneToMany(targetEntity="Main\MainBundle\Entity\Contact", mappedBy="company", cascade={"remove"})
* @ORM\JoinColumn(nullable=true)
*/
private $contacts;
If you don't like to use QueryBuilder you can set your contacts in the controller:
$oForm = $this->createForm(new CompanyForm($contacts));
and in the form you can do this:
public function __construct($contacts))
{
$this->vContacts = $contacts;
}
then:
->add('contacts', 'choice', array(
'required' => true,
'label' => 'contacts',
'choices' => $this->vContacts,
)
)
If you need to get particular set of entities in your form field, you can use query builder.
In your case (inside your form type class) it could be something like:
$builder->add('contacts', 'entity', array(
'class' => 'MainMainBundle:Contact',
'query_builder' => function (EntityRepository $er) use ($company) {
return $er->createQueryBuilder('c')
->where('c.company = :company')
->setParameter('company', $company);
},
));
Pay attention to pass $company
variable.