微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我使用 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 messeges apper 并重新加载页面。所以当页面重新加载时,返回按钮的路由改变了,它是自己的页面

控制器

 /**
 * @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
    ]);
}

将路线名称放在后退按钮中不是一个好主意,因为路线需要类别参数,而一个配方可以有多个类别。

配方表没有类别属性,因为我有一个配方表和类别表之间有 M:M 关系的 recipes_categories 表。

解决方法

我能想到的一种解决方法是将引用者作为查询参数传递,并将其包含在 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(
           $this->request->atrributes->get('_route_params'),$this->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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。