Symfony 如何在 twig 中使用控制器功能?

问题描述

我想在 twig 中使用这个 AdminController:

/**
 * @Route("/admin/user/delete",name="deleteUserById")
 */
public function deleteUserById(Request $request): Response
{
    $id = $request->query->get("id");
    $user = $this->getDoctrine()->getRepository(User::class)->find($id);
    $em = $this->getDoctrine()->getManager();
    $em->remove($user);
    $em->flush();
    return $this->redirectToRoute("getAllUsers");
}

twig 文件如下:

{% extends 'base.html.twig' %}

{% block title %}AdminPanel{% endblock %}
{% block stylesheets %}
    <link href="{{ asset('css/global.css') }}" rel="stylesheet"/>
{% endblock %}
{% block nav %}
<div>
    <a class="navbar-brand" href="{{ path('getAllDoctors') }}">Doctors</a>
    <a class="navbar-brand" href="{{ path('getAllApplications') }}">Applications</a>
    <a class="navbar-brand" href="{{ path('getAllPersons') }}">Persons</a>
    <a class="navbar-brand" href="{{ path('getAllPersons') }}">Admin</a>
</div>
{% endblock %}
{% block body %}
<h1>UserID and Email</h1>

<table class="table">
    <thead class="thead-dark">
    <tr>
        <th scope="col">#</th>
        <th scope="col">Email</th>
        <th scope="col">Delete</th>
    </tr>
    </thead>
    {% for user in users %}
        <tbody>
        <form method="post">
        <td> {{ user.id }}</td>
        <td>{{ user.email }}</td>
        <td>
            <button href=" {{ path('deleteUserById',{'POST' : (user.id)}) }}" 
            type="submit">Delete</button>
        </td>
        </form>
        </tbody>
    {% endfor %}
</table>
{% endblock %}

我希望能够使用删除按钮删除用户。但由于某种原因我无法让它工作? 我读到我需要使用表单,但找不到一个很好的例子。

感谢您的帮助。

解决方法

这不是最好的解决方案,但根据您的代码,您可以这样做:

/**
 * @Route("/admin/user/delete/{id}",name="deleteUserById")
 */
public function deleteUserById(Request $request,$id): Response
{
    $user = $this->getDoctrine()->getRepository(User::class)->find($id);
    $em = $this->getDoctrine()->getManager();
    $em->remove($user);
    $em->flush();
    return $this->redirectToRoute("getAllUsers");
}

树枝

{% for user in users %}
    <tbody>
    <form method="post" action="{{ path('deleteUserById',{'id' : user.id}) }}">
    <td> {{ user.id }}</td>
    <td>{{ user.email }}</td>
    <td>
        <button type="submit">Delete</button>
    </td>
    </form>
    </tbody>
{% endfor %}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...