简体   繁体   中英

Symfony3 update form does not work

Maby a stupid question but i am not seeing it.

I want to change the data from my form, this form contains a relation between a other entity'. While creating a new item, the update function won't work

When i do a var dump on $form->getData(); my browser will crash.

Inside the form->isValid my var_dump doesn't show anything.

Also i tried the $em->merge option, the same result.

Many thanks!

Edit function

 /**
 * @Route("/user/item/edit/{id}")
 */
public function editItemAction($id, Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $item = $em->getRepository('AppBundle:Item')->find($id);

    if (!$item){
        return $this->redirect('/user/item');
    }

    $form = $this->createForm(ItemType::class, $item);

    if ($form->isSubmitted() && $form->isValid()){
        $data = $form->getData();

        $em = $this->getDoctrine()->getManager();
        $em->persist($data);
        $em->flush();

        return $this->redirect('/user/item');
    }

    return $this->render('admin/item/edit.html.twig', [
        'form' => $form->createView()
    ]);
}

Form type

    public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add('category', EntityType::class, array(
    'class' => 'AppBundle:Category',
    'choice_label' => function ($category) {
        return $category->getName();
    }))
    ->add('title', TextType::class)
    ->add('shortText', TextType::class)
    ->add('text', TextType::class)
    ->add('link', TextType::class)
    ->add('active', CheckboxType::class, [
        'required' => false
    ])
    ->add('imageId', TextType::class)
    ->add('Submit', SubmitType::class)
    ->getForm();
}

The includes

use AppBundle\Entity\Category;
use AppBundle\Entity\Item;
use AppBundle\Form\ItemType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityRepository;

You have to handle the request with your form, otherwise $form->isSubmitted() will always return false. So after this line:

$form = $this->createForm(ItemType::class, $item);

you must add:

$form->handleRequest($request);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM