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

Symfony How do I use a controller function in 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");
}

树枝文件如下:

{% 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 %}