Wednesday, May 2, 2012

How to use manytomany field in symfony2?

I am stuck at a point from last 2 days. I am having two entities Subjects and Teachers. There is a manytomany relation between two. i have created a manytomany field in teacher entity like this :-



/**
* @ORM\ManyToMany(targetEntity="College\StudentBundle\Entity\Subjects", inversedBy="assets", cascade={"persist"})
* @ORM\JoinTable(name="employee_subjects")
*/

private $subjects;


which resulted in a third table. My subject entity contains only 3 fields, ID, Department_id and name, Now I want to open a regester form for a teacher where i want add the subjects he can teach, for this i created the subjecttype form ist like this :-



namespace College\StudentBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class SubjectsType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('name')
// ->add('name', 'entity', array('class' => 'CollegeStudentBundle:Subjects', 'property'=>'name', 'multiple' => false, ))
->add('departmentId', 'entity', array('class' => 'CollegeStudentBundle:Department', 'property'=>'name', 'multiple' => false, ))
;
}


public function getName()
{
return 'college_studentbundle_subjectstype';
}
}


And here is my teacher form where i included the subject:-



namespace College\HumanResourceBundle\Form;

use College\StudentBundle\Form\SubjectsType;
use College\StudentBundle\Entity;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class HumanResourceType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('empid')
->add('joining_date', 'date', array('years' => range(date('Y') - 10, date('Y'))))
->add('firstname')
->add('nationality')
->add('usertype', 'entity', array('class' => 'CollegeUserBundle:Usertype', 'property'=>'name', 'multiple' => false, ))

->add('subjects', 'collection', array('type' => new SubjectsType()));
;
}

public function getName()
{
return 'College_humanresourcebundle_humanresourcetype';
}
}

It is not working properly, I want, when i add new teacher it should display subject at the bottom where i can assign subjects to the teacher which gets saved in manytomany table.




1 comment:

  1. 'multiple' => true
    should help u

    ReplyDelete