1

I'm using genemu_jqueryselect2_entity for a multiple selection field within a form (located in an Sonata admin class) for a so called Uni (university) entity:

->add('courses', 'genemu_jqueryselect2_entity',array('multiple' => true, 'class' => 'PROJECT\UniBundle\Entity\Course'))

But the selected entries are not filled into my entity. With firebug I was able to detect, that the ids of the courses are passed correctly via POST.

Maybe the field is not correctly mapped to the Uni entity, but I have no idea why.

This is the adding method of my Uni entity, which doesn't even get called:

public function addCourse(\PROJECT\UniBundle\Entity\Course $courses)
    {
        $this->courses[] = $courses;

        return $this;
    }

How can I get the field to be mapped with the courses attribute of Uni? How could I debug this?

Any help will be appriciated!

enigma
  • 493
  • 2
  • 5
  • 18

4 Answers4

1

Try writing that method like this:

public function addCourse(\PROJECT\UniBundle\Entity\Course $course)
{
    $this->courses[] = $course;
    $course->setUniversity($this); // Or similar.

    return $this;
}

Otherwise foreign key is not set on a course row in the DB.

TautrimasPajarskas
  • 2,686
  • 1
  • 32
  • 40
0

Try to create method setCourses

public function setCourses(\Doctrine\Common\Collections\Collection $courses)
    {
         $this->courses = $courses;
...
Petr Slavicek
  • 446
  • 3
  • 5
0

I don't know why, but the method addCourse isn't called.

Anyway, Tautrimas Pajarskas's answer was usefull to me so I gave an upvote.

The foreign key relationship was the necessary and missing part of my code.

I implemented it in the university sonata admin like this:

private function addUniToCourses ($university) {
    foreach($university->getCourses() as $course) {
        if(!$course->getUniversities()->contains($university)) {
            $course->addUniversity($university);
        }
    }
}

public function prePersist($university) {
        $this->addUniToCourses($university);
}

public function preUpdate($university) {
        $this->addUniToCourses($university);
}

This was the solution to my problem.

enigma
  • 493
  • 2
  • 5
  • 18
0

I had the same problem a while ago: Symfony2, $form->bind() not calling adder methods of entity

Solution: For the adder (addCourse()) to be called, you have to disable the by_reference option of the field:

->add('courses', 'genemu_jqueryselect2_entity',
      array(
          'by_reference' => false, // This line should do the trick
          'multiple' => true,
          'class' => 'PROJECT\UniBundle\Entity\Course'))
Community
  • 1
  • 1
pagliuca
  • 1,129
  • 13
  • 19