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