检索Controller中单个FormType的值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了检索Controller中单个FormType的值相关的知识,希望对你有一定的参考价值。

我在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]);
}
答案

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

以上是关于检索Controller中单个FormType的值的主要内容,如果未能解决你的问题,请参考以下文章

使用连接(codeigniter)从单个字段中检索和打印逗号分隔符后的值

从类型树枝模板中的 FormType 访问变量

如何将参数从控制器传递给 FormType 构造函数

1.《SQL必知必会》--(更新中...)

如何在控制器中检索 POST 数据

仅当 FormType 为 Create 时才将所有者设置为当前用户