I'm not sure about the title but I'll try to explain my problem. I have a small website to manage semesters, classes, students, attendance etc. Built with Symfony 2.3 and Doctrine 2.
Students are enrolled in some classes that I keep like this in my Student entity:
/**
* @ORM\ManyToMany(targetEntity="Course", inversedBy="students")
*/
private $courses;
The website works like this: you select a semester and then the website will only display information related to this semester (i.e. the schedule, the class reports for the classes of this semester etc.). I keep the selected semester in the session.
So it means that when you want to edit a student profile, to enroll her/him in some classes, the choicelist shows only classes for the selected semester (basically the current one), because otherwise you would have too many choices and they would not be accurate.
I generate this select like this, in the StudentType form:
->add('courses', 'entity', array(
'class' => 'VirguleMainBundle:Course',
'query_builder' => $this->doctrine->getRepository('VirguleMainBundle:Course')->getCoursesForSemesterQB($this->semesterId),
'expanded' => false,
'multiple' => true,
'required' => false,
'attr' => array('class' => 'medium-select')
));
But when I submit the form, of course the courses collection is emptied and then filled with the selected choices from the form. It means that enrollement of the student from previous semesters are lost.
I've tried to use a FormEvent, to manually put back the previous saved values, like this:
public function preSubmit(FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
$currentCourses = $form->getData()->getCourses();
foreach ($currentCourses as $course) {
if ($course->getSemester()->getId() != $this->semesterId) {
$data['courses'][] = $course;
}
}
$event->setData($data);
$this->customizeForm($form, false);
}
But then I get an "This value is invalid" error, I guess because I'm adding data that were not in the original form, it makes senses.
So I'd like to know basically how I can show for example classes #20, #21 and #22 (linked to semester #2 that we're currently working on), while keeping already saved values #10, #11 and #12 (because they are linked to the semester #1). Or if there is another solution to achieve this, if I completedy failed at my design.
I hope it makes sense and that someone will help me because I'm stuck :)