-1

An aticle has several variables. A title, a date, visibility and a category. If i render a form with symfony, i want to preselect a category in the dropdownlist. In the controller i have a function :

/**
 * @return Response
 * @route ("/admin/add/{idartikeltype}",name="addbytype")
 */
public function addByType(Request $request, $idartikeltype)
{


    $form = $this->createForm(ArtikelType::class);


    $form->handleRequest($request);



    if ($form->isSubmitted() && $form->isValid()) {

        $item = $form->getData();
        $em = $this->getDoctrine()->getManager();

        $em->persist($item);
        $em->flush();

        return $this->redirectToRoute('lookup');
    }


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

The slug idartikeltype, an integer, contains the id of the category. How must i preselect the correct category in a blanc form?

Ace
  • 31
  • 9

1 Answers1

0

You need to create the item first, set the category and then use it in the form:

$category = $this->em->getRepository(Category::class)->find($categoryId);

$item = new Item();
$item->setCategory($category);

$form = $this->createForm(ArtikelType::class, $item);
Vyctorya
  • 1,387
  • 1
  • 12
  • 18
  • "Entity of type ... must be managed, did u forget to persist it in the enity manager " when i create an object of the Categroy typeand pass it to the $item variable. – Ace Jan 30 '20 at 10:20
  • 1
    @A You don't create a new category. You need to get the category by its id. I updated my answer. – Vyctorya Jan 30 '20 at 12:13