我正在嘗試設置博客,並列出了所有博客條目以及該博客的所有用戶列表。博客的管理員可以從這些列表中刪除單個條目。 無論如何,我遇到的問題是,當選擇一個條目被刪除時,它總是我的列表中的第一個條目被刪除,而不是我實際選擇的條目。通過Symfony中的ID刪除單個主義條目
這裏是我的deleteAction:
/**
* @Route("/blog/delete/{id}", name="entrydelete", requirements={"id" = "\d+"}, defaults={"id" = 0})
*
*/
public function deleteAction(Request $request, Blog $blog) {
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($blog);
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $entry->getAuthor() == $this->getUser()->getUsername()) {
$em->remove($entry);
$em->flush();
return $this->render('BlogBundle:blog:deletesubmit.html.twig');
}
else {
return $this->render('BlogBundle:blog:error.html.twig');
}
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults([
'data_class' => 'BlogBundle\Entity\Blog'
]);
}
和根據樹枝模板:
{% for blog in bloglist %}
<h4>{{ blog.title }}</h4>
<p><span class="fa fa-clock-o"></span> Posted on {{ blog.date|date('d.M Y H:i A') }} </p>
<p><span class="fa fa-user-circle"></span> Posted by {{ blog.author }} </p>
<p>{{ blog.text }}</p>
<button type="button" class="btn btn btn-info">
<a href="{{ path('entryedit', {'id':blog.id}) }}" style="color: #FEFEFE">Edit entry</a>
</button>
<button type="button" class="btn btn btn-warning">
<a href= "#myModal" role="button" data-toggle="modal" style="color: #FEFEFE">Delete entry</a>
</button>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title" id="myModalLabel">Are you sure?</h3>
</div>
<div class="modal-body">
<p>Do you really want to delete this profile?</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">
Go Back
</button>
<button type="button" class="btn btn btn-warning">
<a href="{{ path('entrydelete', {'id':blog.id}) }}" style="color: #FEFEFE">Yes</a>
</button>
</div>
</div>
</div>
</div>
<hr>
{% endfor %}
所以我只想澄清這一點:如果我有一個這樣的名單: 1,條目1 2。條目2 3.條目3 我想刪除條目3,選擇那個並確認,條目1不見了。
會很高興任何形式的幫助!
感謝邁克爾,完美地解決了我的問題!我願意爲可以添加的任何優化工作而開放,所以如果對你沒有太多的努力,請隨時與我分享。 – sonja
很高興幫助!一些優化可能與代碼風格有關。我會盡力將其添加到我的答案中,並讓你知道。 –
@sonja我在此頁面上重新格式化了一些控制器的代碼(在頁面底部的註釋):https://gist.github.com/michaelperrin/4771f2857fadfd43e2af6487efd986fa –