0

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

    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. 隐藏字段并提供额外的图像实体以进行渲染

还有什么我可以做得更好的吗?

问候

4

1 回答 1

1

(我的回答对于评论来说太长了,所以我在这里添加)

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

<?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();
}

希望我足够清楚

于 2012-04-27T15:18:32.630 回答