【发布时间】:2021-05-08 04:12:00
【问题描述】:
我的 Symfony5 应用程序有问题。 提交表单后,页面刷新,没有任何反应。下面的代码有什么问题?我试图调试它并检查控制器哪里有错误,但我找不到它。在探查器中,我看不到带有 INSERT 的查询,只有 SELECT。
主题控制器:
/**
* @param Request $request
* @Route("/custom", name="custom")
*/
public function custom(Request $request)
{
$form = $this->createFormBuilder()
->add('title', TextType::class, [
'label' => 'Tytuł tematu'
])
->add('description', TextareaType::class, [
'label' => 'Opis tematu',
'attr' => [
'rows' => 5,
'placeholder' => 'Opis tematu...'
]
])
->add('submit', SubmitType::class, [
'attr' => [
'class' => 'btn btn-success btn-block'
],
'label' => 'Zarezerwuj'
])
->add('category', ChoiceType::class, [
'choices' => [
'PWA' => 'PWA',
'RWA' => 'RWA',
'SPA' => 'SPA',
'RIA' => 'RIA',
'REST' => 'REST',
'PHP REST' => 'PHP REST',
'Inna' => 'Inna'
],
'label' => 'Kategoria'
])
->add('techDescription', TextType::class, [
'label' => 'Opis technologii',
'attr' => [
'placeholder' => 'Opis technologii...'
],
'required' => FALSE
])
->getForm();
$form->handleRequest($request);
$form->getErrors();
$topic = new Topic();
$reservation = new Reservation();
if ($form->isSubmitted()) {
if ($form->isValid()) {
$data = $form->getData();
$em = $this->getDoctrine()->getManager();
$topic->setCreatedAt(new \DateTime());
$topic->setUpdatedAt(new \DateTime());
$topic->setCustom(TRUE);
$topic->setTitle($data['title']);
$topic->setTopicDescription($data['topicDescription']);
$em->persist($topic);
$em->flush();
$reservation->setUpdatedAt(new \DateTime());
$reservation->setCreatedAt(new \DateTime());
$reservation->setUser($this->getUser());
$reservation->setCategory($data['category']);
if (!empty($data['techDescription']))
$reservation->setTechDescription($data['techDescription']);
$reservation->setTopic($topic);
$em->persist($reservation);
$em->flush();
if ($reservation->getId() == NULL) {
$em->remove($topic);
$em->flush();
$this->addFlash('error', 'Posiadasz już aktywną rezerwację');
return $this->redirectToRoute('topic.custom');
}
return $this->redirectToRoute('home');
} else {
$this->addFlash('error','Issue with validation');
}
}
return $this->render('topic/custom.html.twig', [
'form' => $form->createView()
]);
custom.html.twig:
{% extends('base.html.twig') %}
{% block content %}
<div class="container mt-4 mb-4 pl-4 pr-4">
<form class="col-md-6 mx-auto" method="" action="">
<input type="hidden" name="token" value="{{ csrf_token('custom') }}"/>
<div class="form-group">
{{ form_row(form.title) }}
</div>
<div class="form-group">
{{ form_row(form.description) }}
</div>
<div class="form-group">
{{ form_row(form.category) }}
<div class="mt-3" id="techDesc" style="display:none">
{{ form_row(form.techDescription) }}
</div>
</div>
{{ form_row(form.submit) }}
</form>
</div>
{% endblock %}
【问题讨论】:
-
对于 symfony 和 symfony 表单有一些很好的指南。你显然错过了他们,这让我很难过。例如
method=""根本没有任何意义。 POST怎么样?默认情况下,表单具有 csrf-protection,但您不使用表单标签来构建 -
@Jakumi,感谢您的提示 - 顺便说一句,通过向方法添加帖子解决了问题。没有缺少 csrf 保护,有 csrf_token 的隐藏输入
-
哦,跳过了,好像;o)