sectus
sectus

Reputation: 15464

How to avoid "Entities passed to the choice field must be managed. Maybe persist them in the entity manager?"

  1. Generated Entities from existing database
  2. Generated CRUD controller

But it does not work with exception message:

Entities passed to the choice field must be managed. Maybe persist them in the entity manager?

Entity

/**
 * Question
 *
 * @ORM\Table(name="question", indexes={@ORM\Index(name="question_category_id", columns={"question_category_id"})})
 * @ORM\Entity
 */
class Question
{
    //...

    /**
     * @var \AppBundle\Entity\QuestionCategory
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\QuestionCategory")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="question_category_id", referencedColumnName="id")
     * })
     */
    private $questionCategory;

    public function __construct() 
    {
        $this->questionCategory = new QuestionCategory();
    }

    //...
}

Form

class QuestionType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('questionCategory');
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Question'
        ));
    }
}

Controller

class QuestionController extends Controller
{
   //...

   /**
     * Creates a new Question entity.
     * @Route("/new", name="question_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $question = new Question();
        $form = $this->createForm('AppBundle\Form\QuestionType', $question);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($question);
            $em->flush();

            return $this->redirectToRoute('question_show', array('id' => $question->getId()));
        }

        return $this->render('question/new.html.twig', array(
            'question' => $question,
            'form' => $form->createView(),
        ));
    }

//...
}

Deep debugging gives nothing to me. How to fix it?

Test repository to reproduce error: https://github.com/sectus/question.test.local

Upvotes: 8

Views: 25150

Answers (6)

Marco Valeri
Marco Valeri

Reputation: 491

There are different reasons that create this issue.

In my case, I fixed it changing

by_reference' => false

to

by_reference' => true

in the CRUD controller.

Upvotes: 4

Cmalfr
Cmalfr

Reputation: 61

In my case I was having this issue because I was using EntityType instead of ChoiceType, to build the selectList.

EntityType display only data from database, instead ChoiceType can display "not managed" objects.

I hope this will help.

Upvotes: 5

Roubi
Roubi

Reputation: 2106

Beware, this error can also be raised when using 'by_reference' => false, in your form type with relations that are not ManyToMany.
An unfortunate copy/paste put me in this situation.

Upvotes: 13

maro_echeverria
maro_echeverria

Reputation: 1

In my case, it just was because by my fault I was using the QueryManager instead of EntityManager to find the entity in my controller.

Upvotes: 0

Terenoth
Terenoth

Reputation: 2598

This error means the attribute questionCategory which is a relationship, is not managed by the EntityManager. For this to be done automatically, add a cascade-persist in your Doctrine Mapping for questionCategory attribute:

Entity

/**
 * Question
 *
 * @ORM\Table(name="question")
 * @ORM\Entity
 */
class Question
{
    //...

    /**
     * @ORM\ManyToOne(
     *       targetEntity="QualityBundle\Entity\QuestionCategory", 
     *       cascade={"persist"}
     * )
     */
    private $questionCategory;

    //...
}

This way, when you call $em->persist($question);, the QuestionCategory linked to your Question will automatically be persisted as well.

Upvotes: 3

Oscar Pérez
Oscar Pérez

Reputation: 4397

According to the code shown on your GitHub project, the Question entity has the following constructor:

public function __construct() 
{
    $this->questionCategory = new QuestionCategory();
}

When you create an entity form field, it can only contain values that are managed by doctrine, but your new questionCategory is not managed.

Usually, the best solution is just to not fill this entity field in the constructor, but only in those places you strictly need it. When building a form, Synfony will fill it for you after submitting and calling $form->handleRequest().

So, in your case, just remove the Question entity's constructor.

After that, you'll also need to implement the __toString() method in QuestionCategory entity:

 public function __toString(){
       return 'whatever you neet to see the type`;
 }

Upvotes: 8

Related Questions