如何在使用 Symfony 表单提交按钮时从 HTML 表单请求数据

How to request data from HTML form while using Symfony form for submit button

我使用的是仅用于提交和取消按钮的 Symfony 混合表单,其中任何用户输入数据都是通过 HTML 发送的。

这是我获取请求的控制器代码。它检索 save 按钮是否被正常点击,但它为 $content

传递 null
$form = $this->createForm(FormType::class)
        ->add('save', SubmitType::class, array('label'=> 'Save changes form',
            'attr' => ['class' => 'btn btn-primary']));
    $form->handleRequest($request);
    if ($form->get('save')->isClicked()){
        if ($form->isValid()){
            $content = $request->get('content');
            $announcementToCreate = new Announcement($content, $currentUser);
            $currentUser->getAnnouncements()->add($announcementToCreate);
            $this->getDoctrine()->getManager()->persist($announcementToCreate);
            $this->getDoctrine()->getManager()->flush();

这是我的 twig/html 代码。我正在为此表单使用模式。我能够使用纯 html.

获得所需的结果
<div class="modal-body">
    {{ form(form) }}
    {{ form_start(form) }}
        <textarea class="form-control" id="announcementText" rows="5" name="contents"></textarea>
        {{ form_end(form) }}
  1. 您需要将文本区域输入添加到表单中:
$form = $this->createForm(FormType::class)
    ->add('content', TextareaType::class, [
        'label' => false,
        'attr' => [
            'rows' => 5,
            'class' => 'form-control'
        ]
    ])
    ->add('save', SubmitType::class, [
        'label'=> 'Save changes form',
        'attr' => ['class' => 'btn btn-primary']
    ]);

  1. {{ form(form) }} 用于完整的表单渲染,您不需要将它与 form_start/form_end.
  2. 一起使用

只做一个完整的表单渲染:

{{ form(form) }}

或单独呈现表单的每个部分:

{{ form_start(form) }}

  {{ form_row(form.content) }}
  {{ form_row(form.submit) }}

{{ form_end(form) }}
  1. 您无需检查您的按钮是否有 "click",只需检查您的表单是否已提交:
...

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {

    // You can get your data directly from the form:   
    $content = $form->get('content')->getData();

    $announcementToCreate = new Announcement($content, $currentUser);
    $currentUser->getAnnouncements()->add($announcementToCreate);
    $this->getDoctrine()->getManager()->persist($announcementToCreate);
    $this->getDoctrine()->getManager()->flush();
}