检索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的值的主要内容,如果未能解决你的问题,请参考以下文章