Symfony2:通过邮寄请求删除实体(需要改进)

时间:2012-04-27 11:49:42

标签: forms symfony controller entity

我需要对删除实体的实际方法进行一些改进:

    public function deleteAction($path)
    {
    $form = $this->createFormBuilder(array('path' => $path))
        ->add('path')
        ->setReadOnly(true)
        ->getForm();

    if ($this->getRequest()->getMethod() === 'POST') {
        $form->bindRequest($this->getRequest());

        if ($form->isValid()) {
            $image = $this->getImageManager()->findImageByPath($path);
            $this->getImageManager()->deleteImage($image);

            return $this->redirect($this->generateUrl('AcmeImageBundle_Image_index'));
        }
    }

    return $this->render('AcmeImageBundle:Image:delete.html.twig', array(
        'form' => $form->createView(),
    ));
}

我在写作时已经找到了两项改进:

  1. 在控制器中的额外方法中使用CreateFormBuilder

  2. 隐藏字段并覆盖额外的图像实体以进行渲染

  3. 还有其他我可以做得更好的事吗?

    此致

1 个答案:

答案 0 :(得分:1)

(我的答案对于评论太长了所以我在这里添加)

首先,您必须创建一个Type文件(通常在YourApp \ YourBundle \ Form \ yourHandler.php中),如果您不知道,可以使用一些basique代码:

<?php
namespace ***\****Bundle\Form;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;

use ***\****Bundle\Entity\your_entity;

class *****Handler
{
protected $form;
protected $request;
protected $em;

public function __construct(Form $form, Request $request, EntityManager $em)
{
    $this->form    = $form;
    $this->request = $request;
    $this->em      = $em;
}

public function process()
{
    if( $this->request->getMethod() == 'POST' )
    {
        $this->form->bindRequest($this->request);

        if( $this->form->isValid() )
        {
            $this->onSuccess($this->form->getData());

            return true;
        }
    }

    return false;
}

public function onSuccess(your_entity $object)
{
    // Make your stuff here (remove,....)
}
}

在你的控制器中我只是这样称呼它:

if (!empty($_POST))
{
    $formHandler = new *****Handler($my_form, $this->get('request'), $this->getDoctrine()->getEntityManager());
    $formHandler->process();
}

希望我足够清楚