首页 > 解决方案 > 在控制器中检索单个 FormType 的值

问题描述

我的 FormType 中有一个字段,我试图获取它成功提交时的值并将其传递给我的控制器。我通过将变量传递给表单并使用attr文本框将其设置为中的相应值来设置字段的值$options,html的最终结果是 <input type="hidden" id="listing_editId" name="listing[editId]" required="required" value="1288701182" readonly="readonly">

列表类型.php

    ->add('editId', HiddenType::class, [
      'required' => true,
      'disabled' => false,
      'mapped' => true,
      'attr' => [
        'value' => $options['editId'],
        'readonly' => true,
      ]
    ])

我试过$form->get('editId');但它没有返回值,我也试过$request->get('editId');无济于事。

清单控制器.php

/**
 * @Route("/account/listings/create", name="listing_create")
 */
public function createAction(Request $request)
{
    $r = sprintf('%09d', mt_rand(0, 1999999999));
    $form = $this->createForm(ListingType::class, null, [
        'currency' => $this->getParameter('app.currency'),
        'hierarchy_categories' => new Hierarchy($this->getDoctrine()->getRepository('AppBundle:Category'), 'category', 'categories'),
        'hierarchy_locations' => new Hierarchy($this->getDoctrine()->getRepository('AppBundle:Location'), 'location', 'locations'),
        'editId' => $r,
    ]);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $listing = $form->getData();
        $listing->setUser($this->getUser());

        try {
            $em = $this->getDoctrine()->getManager();
            $em->persist($listing);
            // I'd like to be able to get the value of an input field that is "editId" here
            $em->flush();
            $this->addFlash('success', $this->get('translator')->trans('Listing has been successfully created.'));
        } catch (\Exception $e) {
            $this->addFlash('danger', $this->get('translator')->trans('An error occurred when creating listing object.'));
        }

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

    return $this->render('FrontBundle::Listing/create.html.twig', [
      'form'  => $form->createView(),
      'editId' => $r]);
}

标签: phpformssymfonycontroller

解决方案


尝试$form->get('editId')->getData()$request->request->get('editId')$form->getData()['editId']


推荐阅读