【发布时间】:2021-05-04 17:45:13
【问题描述】:
我想在提交后清理 Symfony 表单的值字段,但我不知道该怎么做。
表格文件
<?php
namespace App\Form;
use App\Entity\Comment;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class CommentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('text',TextareaType::class)
->add('visible',HiddenType::class)
->add('user',HiddenType::class)
->add('recipe',HiddenType::class)
->add('save', SubmitType::class, [
'label' => "Comentar",
'attr' => ['class' => 'save'],
]);
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Comment::class,
]);
}
}
控制器文件
/**
* @Route("/receta/{title}", name="recipe_show", methods={"GET"})
* @Route("/receta/{title}", name="recipe_show")
*/
public function show(Recipe $recipe,RecipeRepository $recipeRepository,CommentRepository $commentRepository, Request $request): Response
{
$comment = new Comment();
$comment_form = $this->createForm(CommentType::class, $comment);
$comment_form->handleRequest($request);
if ($comment_form->isSubmitted() && $comment_form->isValid()) {
$comment->setVisible(0);
$user = $this->getUser();
$comment->setUser($user);
$comment->setRecipe($recipe);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
$this->addFlash('success', '¡Comentario registrado con exito! Tu comentario estará visible una vez que el administrador lo revise.');
}
$comments = $commentRepository->findCommentsByRecipe($recipe);
return $this->render('recipe/show/show.html.twig', [
'recipe' => $recipe,
'comment_form' => $comment_form->createView(),
'comments' => $comments
]);
}
具体来说,我需要在提交后清理文本字段,但我不知道该怎么做。我也需要在提交后显示一个addFlash。在这个过程中不能错过。我该如何解决?
【问题讨论】:
-
这就是文档在提交并成功处理表单后显示重定向的原因。相同的文档还显示了使用 Flash 消息功能。
-
@Cerad 你能给我它所在的 URL 文档吗?我没有看到两者结合的例子
-
@FTW 我试过了,但它对我不起作用。我使用 Symfony 4.4
-
解决了。谢谢 Cerad!
标签: forms symfony field symfony4 symfony-forms