如何在重新加载Symfony/twig后创建返回按钮

4c8rllxm  于 2022-12-04  发布在  其他
关注(0)|答案(2)|浏览(150)

我使用Symfony 4.4。我在我的Twig模板中有一个返回按钮。

{% if previousPageboolean == false %}
        <a class="d-block text-decoration-none cursor px-4 pt-3" href="{{app.request.headers.get('referer')}}"><img src="{{ asset('build/images/back.svg')}}" class="height-19"></a>
{%else%}
        <a class="d-block text-decoration-none cursor px-4 pt-3" href="{{referer}}"><img src="{{ asset('build/images/back.svg')}}" class="height-19"></a>
{% endif %}

但我有一个问题。它的工作,但在这个模板中,我有2个表单。当我点击这些按钮的提交按钮时,Flash消息会弹出并重新加载页面。因此,当页面重新加载时,返回按钮的路线会发生变化,它是自己的页面。
主计长

/**
 * @Route("/receta/{title}", name="recipe_show", methods={"GET"})
 * @Route("/receta/{title}", name="recipe_show")
 */
public function show(Recipe $recipe,RecipeRepository $recipeRepository,ScoreRepository $scoreRepository,CommentRepository $commentRepository, Request $request): Response
{ 
    $comment = new Comment();
    $score = new Score();

    $comment_form = $this->createForm(CommentType::class, $comment);
    $comment_form->handleRequest($request);
    
    $score_form = $this->createForm(ScoreType::class, $score);
    $score_form->handleRequest($request);

    $entityManager = $this->getDoctrine()->getManager();
    $user = $this->getUser();

    $referrer="";
    $previousPageboolean =false;

    if ($score_form->isSubmitted() && $score_form->isValid()) {  
        $previousPageboolean =true;
        $referrer = $request->get('referrer');

        $score_value = $score_form->get("score")->getData();

        $isScore = $scoreRepository->findBy(array('user' => $user , 'recipe' => $recipe->getId()));
        
        if($isScore == [] ){
            $score->setScore($score_value); 
            $score->setRecipe($recipe); 
            $score->setUser($user);
            $entityManager->persist($score); 
            $entityManager->flush();  

            $this->addFlash('success', '¡Puntuación registrada con exito!');
            return $this->redirectToRoute($request->getUri(), [
                'referrer' => $this->generateUrl($request->attributes->get('_route'),
                   array_merge(
                       $this->request->atrributes->get('_route_params'),
                       $this->request->query->all
                   ), 
                ),
            ]);  
        }else{
            $this->addFlash('danger', 'Ya existe una puntuación registrada para esta receta con este usuario.');
            return $this->redirect($request->getUri()); 
        }              
    }   

    if ($comment_form->isSubmitted() && $comment_form->isValid()) {
        $parentid = $comment_form->get("parent")->getData();

        if($parentid != null){
            $parent = $entityManager->getRepository(Comment::class)->find($parentid);
        }

        $comment->setVisible(1);
        $comment->setParent($parent ?? null);
        $comment->setUser($user);
        $comment->setRecipe($recipe);
        $comment->setCreatedAt(new DateTime());        
        $entityManager->persist($comment);
        $entityManager->flush();  

        $this->addFlash('success', '¡Comentario registrado con exito!');
        return $this->redirect($request->getUri());     
    }

    $comments = $commentRepository->findCommentsByRecipe($recipe);

    return $this->render('recipe/show/show.html.twig', [
        'recipe' => $recipe,
        'score_form' => $score_form->createView(),
        'comment_form' => $comment_form->createView(),
        'comments' => $comments,
        'referrer' => $referrer,
        'previousPageboolean' => $previousPageboolean
    ]);
}

最好不要将路线名称放在后退按钮中,因为路线需要类别参数,而一个配方可以有多个类别。
recipe表没有category属性,因为我有一个recipes_categories表,它在recipe表和category表之间具有M:M关系。

68bkxrlz

68bkxrlz1#

不知道这是否与您的问题有关,但我认为您的控制器中有一个打字错误:如果您有一个请求,那么您可以使用这个请求来创建一个数组。

daolsyd0

daolsyd02#

我能想到的一个解决方法是将referer作为查询参数传递,并将其包含在twig文件中。
如果您从twig重定向到当前控制器:

<a href="{{path('some_path', {..., 'referrer': path(app.request.get('_route'), app.request.get('_route_params')|merge(app.request.query.all)))})}}">Link to the current controller</a>

如果您使用RedirectResponse进行重定向:

return $this->redirectToRoute('some_path', [
    ...,
    'referrer' => $this->generateUrl($request->attributes->get('_route'),
       array_merge(
           $request->atrributes->get('_route_params'),
           $request->query->all
       ), 
    ),
]);

控制器:

public function show(Request $request, ...)
{
...
$referrer = $request->get('referrer');
...

return $this->render('recipe/show/show.html.twig', [
    ...,
    'referrer' => $referrer,
]);

小枝:

<a class="d-block text-decoration-none cursor px-4 pt-3" href="{{referrer}}"><img src="{{ asset('build/images/back.svg')}}" class="height-19"></a>

相关问题