检索Controller中单个FormType的值

问题描述 投票:0回答:1

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

ListingType.php

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

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

ListingController.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]);
}
php forms symfony controller
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.