我想在当前会话中添加带有用户名的隐藏字段。用户名在另一个名为User的实体中。怎么解决?
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class, array('required' => false))
->add('description', TextareaType::class, array(
'required' => false,
'attr' => array('style' => 'resize: none')))
->add('imageFile', FileType::class);
}
public function addPhotoAction(Request $request)
{
$photo = new Photo();
$user = $this->getUser()->getId();
$form = $this->createForm(PhotoFormType::class, $photo);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$em = $this->getDoctrine()->getManager();
$em->persist($photo);
$em->flush();
$this->addFlash('success', 'You\'ve shared a photo!');
return $this->redirectToRoute('homepage');
}
return $this->render('pages/addPhoto.html.twig', [
'photoForm' => $form->createView(),
'user' => $user
]);
}
如何将userId添加到$ builder? id(用户表)必须在addedBy(照片表)中。我要做一个关系?
答案 0 :(得分:0)
您可以将数据推送到表单字段。如果为表单对象添加隐藏字段,它看起来就像这些行。
$form = $this->createForm(PhotoFormType::class, $photo);
$form->get('usernameField')->setData($this->getUser()->getUsername());