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

Php Symfony如何在twig中使用控制器功能?,php,twig,symfony4,Php,Twig,Symfony4,我想在twig中使用此AdminController: /** * @Route("/admin/user/delete", name="deleteUserById") */ public function deleteUserById(Request $request): Response { $id = $request->query->get("id"); $user = $this->ge

我想在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");
}
小枝


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

/**
 * @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");
}
小枝


仅供参考:如果您想在twig模板中使用PHP代码,可以创建一个扩展twig\Extension\AbstractExtension的AppExtension类。在AppExtension中,您创建了一些函数,上面是:您可以注入服务。仅供参考:如果您想在twig模板中使用PHP代码,您可以创建一个AppExtension类来扩展twig\Extension\AbstractExtension。在AppExtension中,您创建了一些函数和顶层:您可以注入服务。