0

单击链接时,我在我的 AlbumController 中传递了一个对象 ID:

<?php

namespace YM\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class AlbumController extends Controller
{
    public function deleteAction($id)
    {

        if ($id > 0) {
            // We get the EntityManager
            $em = $this->getDoctrine()
                       ->getEntityManager();

            // We get the Entity that matches id: $id
            $article = $em->getRepository('YMTestBundle:Album')
                          ->find($id);

            // If the Album doesn't exist, we throw out a 404 error
            if ($article == null) {
              throw $this->createNotFoundException('Album[id='.$id.'] do not exist');
            }


              // We delete the article
            $em->remove($article);
            $em->flush();

            $this->get('session')->getFlashBag()->add('info', 'Album deleted successfully');

              // Puis on redirige vers l'accueil
              return $this->redirect( $this->generateUrl('ymtest_Artist') );
        }
        return $this->redirect( $this->generateUrl('ymtest_dashboard') );
    }
}

它有效。

但是在stackoverflow上看到了一些东西,他们传递了一个我想重现的对象(我听说S2能够自己找到它):

<?php

namespace YM\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class AlbumController extends Controller
{
    public function deleteAction(Album $album)
    {
        // We get the EntityManager
        $em = $this->getDoctrine()
                   ->getEntityManager();

        // If the Album doesn't exist, we throw out a 404 error
        if ($lbum == null) {
          throw $this->createNotFoundException('Album[id='.$id.'] do not exist');
        }


          // We delete the article
        $em->remove($album);
        $em->flush();

        $this->get('session')->getFlashBag()->add('info', 'Album deleted successfully');

          // Puis on redirige vers l'accueil
          return $this->redirect( $this->generateUrl('ymtest_Artist') );

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

但它不起作用,我有:

类 YM\TestBundle\Controller\Album 不存在

为什么 ?谢谢

4

1 回答 1

4

首先你忘记了使用声明:

use  YM\TestBundle\Entity\Album;

在您的情况下,symfony 在当前命名空间(即 Controller)中查找 Album 类。

Moveover,您可能需要阅读有关 ParamConverter (您询问的机制)的更多信息:

http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html

尝试在您的方法注释中添加类似的内容(并且不要忘记此注释的适当命名空间):

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

(...)

/**
 * @ParamConverter("album", class="YMTestBundle:Album")
 */
public function deleteAction(Album $album)
{
   (...)

于 2013-02-06T23:02:20.130 回答