我想动态删除帖子功能,但结果是错误,因为值为空。
控制器
/**
* @Route("/posts/delete/{id}", name="delete_post", methods={"DELETE"})
*/
public function deletePost($id, LoggerInterface $logger)
{
$post=$this->getDoctrine()->getRepository(Article::class)->find($id);
if(!$post)
{
$this->addFlash(
'notice',
'Something went wrong'
);
$logger->info($id);
}
else
{
$entityManager=$this->getDoctrine()->getManager();
$entityManager->remove($post);
$entityManager->flush();
$entityManager->clear();
}
$response=new Response();
return($response);
}
JS
const articles = document.getElementById("articles");
if (articles) {
articles.addEventListener("click", e => {
if (e.target.className === "btn btn-danger delete-article") {
if (confirm("Are you sure?")) {
const id = e.target.getAttribute("data-id");
fetch("/posts/delete/${id}", {
method: "DELETE"
}).then(res => window.location.reload());
}
}
});
}
枝条
<table border="1" id="articles">
<tr>
<th class="pt">Post title</th>
<th class="pe">Edit</th>
<th class="pd">Delete</th>
</tr>
{% for article in articles %}
<tr>
<td class="title">{{ article.title }}</td>
<td class="edit">
<a href="{{ path('posts_editor', {'id':article.id}) }}" class="btn btn-primary edit-article">
<img src="{{ asset('images/edit.png') }}" class="image">
</a>
</td>
<td class="delete">
<a href="#" class="btn btn-danger delete-article" data-id="{{article.id}}">
<img src="{{ asset('images/delete.png') }}" class="image">
</a>
</td>
</tr>
{% endfor %}
</table>
我是用视频教程做的,我不知道视频上有什么问题,这段代码正在运行,但是当我写它时,我在下面遇到了一个错误
错误
EntityManager#remove() 期望参数 1 是一个实体对象,给定 NULL。
希望任何人都可以帮助我,因为它不起作用,我真的很沮丧。
慕尼黑8549860
相关分类