1

I'm trying to save my ManyToMany relations between users and categories. Actually I'm trying to save my category with given users, but this doesn't work.

Form

$builder->add('name')
        ->add('users', EntityType::class, array(
            'label' => 'Benutzer',
            'class' => 'AppBundle\Entity\User',
            'multiple' => true,
            'expanded' => true,
            'required' => false,
            'choice_label' => function (User $user) {
                return $user->getUsername();
            }
        ))
        ->add('submit', SubmitType::class, array(
            'label' => 'Speichern'
        ));

Form Handler

public function onSuccess(Request $request)
{
    // Get category from form
    $category = $this->getForm()->getData();

    // Redirect to parent category when setted
    if ($this->parent) {
        $category->setParent($this->parent);
        $response = new RedirectResponse($this->router->generate('categories.view', [
            'category' => $this->parent->getId()
        ]));
    } else {
        // Build new redirect response
        $response = new RedirectResponse($this->router->generate('categories.view', [
            'category' => $category->getId()
        ]));
    }

    try {
        // Save category in database
        $this->em->merge($category);
        $this->em->flush();
    } catch (ORMException $ex) {
        throw $ex;
    }

    return $response;
}
Community
  • 1
  • 1
Max Heyer
  • 135
  • 2
  • 8

1 Answers1

1

Maybe you have to unserialize the Entity $category first?

$detachedCategory = unserialize($category); 
$this->em->merge($detachedCategory);
$this->em->flush();

I found this link regarding that: How to manage deserialized entities with entity manager?

Not sure if that's the answer, but you might want to do more research.

Community
  • 1
  • 1
Alvin Bunk
  • 7,621
  • 3
  • 29
  • 45
  • Thank your for your fast answer. This does not help, my $category variable isn't serialized: "Warning: unserialize() expects parameter 1 to be string, object given" – Max Heyer Dec 02 '16 at 19:25
  • What if you use `$this->em->persist($category);` instead? Or do you have to use merge? – Alvin Bunk Dec 02 '16 at 21:42
  • unserialize does throw this exception, because my $category variable is an instance of Entity, not a serialized string. – Max Heyer Dec 02 '16 at 21:48