Symfony 3中使用Twig的删除操作

6

所以我从CRUD生成器中复制了基本的删除操作:

   /**
    * @Route("category/delete/{id}", name="category_delete")
    * @Method("DELETE")
    */
    public function deleteAction(Request $request, $id)
    {
        $repository = $this->getDoctrine()->getRepository('AppBundle:Category');
        $category = $repository->find($id);

        $form = $this->createDeleteForm($category);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($category);
            $em->flush();
        }

        return $this->redirectToRoute('category_index');
    }

    /**
     *
     * @param Category $category
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(Category $category)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('category_delete', array('id' => $category->getId())))
            ->setMethod('DELETE')
            ->getForm()
            ;
    } 

然而,我不确定如何实际使用该操作。 我想在两个位置进行删除,但我不确定正确的方法是什么:
1. 在编辑操作中删除 - 如何向表单构建器添加删除按钮?我必须在twig模板本身中执行吗? 2. 在索引中删除 - 我知道如何调用操作(例如,<a href="{{ path('category_edit', {'id': cat.id}) }}" class="btn btn-default">Edit</a>),但这对于删除操作无效。
我已经尝试查看 Symfony演示应用程序,但我仍然不完全了解删除操作的工作方式 - 我找不到文档中的任何内容。
有人能提供有关删除操作在1和2方面如何工作的简要说明吗?
1个回答

7
Symfony CRUD 的删除脚本需要通过表单提交来完成,因此您需要渲染一个表单以显示删除按钮。
您可能会犹豫是否要为列表中的每个项目都渲染一个表单。将表单嵌入编辑表单中也不方便。
借助 Bootstrap 模态框(用于确认删除)和 ajax 提交,我找到了以下解决方案:
1. 将您的 deleteAction 支持 GET,以便在必要时渲染表单。 2. 在需要删除链接的任何地方,将其作为模态框的链接,该模态框将加载 deleteAction 控制器以在模态框主体中呈现表单。您也可以在模态框中添加确认消息。 3. 当模态框表单被提交时,相应地处理您的 deleteAction 脚本,并进行重定向。 编辑:添加了 ControllerTemplate 的脚本。
/**
 * @Route("category/delete/{id}", name="category_delete")
 * @Method({"GET", "DELETE"})
 */
public function deleteAction(Request $request, $id)
{
    /*
     * Check Permission.
     */
    $response = array(
        'success' => true,
        'message' => '',
        'html' => '',
    );

    $repository = $this->getDoctrine()->getRepository('AppBundle:Category');
    $category = $repository->find($id);

    $form = $this->createDeleteForm($category);
    if ($request->getMethod() == 'DELETE') {
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($category);
            $em->flush();

            // Get response ready as per your need.
            $response['success'] = true;
            $response['message'] = 'Deleted Successfully!';
        } else {
            $response['success'] = false;
            $response['message'] = 'Sorry category could not be deleted!';
        }
        return new JsonResponse($response);

        // In case you want to redirect.
        // $this->addFlash('notice', 'Deleted Successfully!');
        // return $this->redirectToRoute('category_index');
    }
    $render = $this->render(':category:delete_confirm.html.twig', array(
        'delete_form' => $form->createView(),
        'category' => $category,
    ));

    $response['html'] = $render->getContent();

    return new JsonResponse($response);
}

使用Twig HTML代码返回模态框(我正在使用UIKIT模态框)

{{ form_start(delete_form) }}
<div class="uk-modal-header">
    <h3 class="uk-modal-title">Delete this Category?</h3>
</div>
<p>
    Are you sure you want to delete  '{{ category.name }}'?<br/>
    This cannot be undone.
</p>
<div class="uk-modal-footer uk-text-right">
    <div>
        <button type="submit" class="md-btn md-btn-danger" title="Click to proceed!">
            <i class="uk-icon-trash"></i> Delete
        </button>
        <button type="button" class="md-btn md-btn-warning uk-modal-close">Cancel</button>
    </div>
</div>
{{ form_end(delete_form) }}

希望这能帮助到您!

如果您能分享一些代码,那就太好了,我对Ajax并不是非常熟悉。 - Darkstarone
2
已添加控制器和模板的脚本。您可以使用jQuery动态呈现模态框并提交表单。 - Jeet
非常感谢,这非常有用。我在弄删除按钮的HTML方面遇到了一些问题,您能否也添加一下? - Darkstarone
另外,你的createDeleteForm方法和我的完全一样吗? - Darkstarone
1
createDeleteForm 函数类似。删除按钮属性取决于您如何调用动态引导模态框。我有一个不同的脚本来处理应用程序中所有ajax模态框,使用UIKIT。因此,按钮属性完全不同,并根据我的脚本进行了定制。请参考此链接或搜索动态引导模态框。 - Jeet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接