使用CRUD控制器

时间:2017-05-10 11:18:42

标签: php symfony sonata-admin symfony-sonata sonata

我想在Sonata管理包中创建一个自定义页面树枝(例如克隆):

enter image description here

我使用本教程:

http://symfony.com/doc/current/bundles/SonataAdminBundle/cookbook/recipe_custom_action.html

这是我的控制器CRUDController.php

<?php
// src/AppBundle/Controller/CRUDController.php

namespace AppBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController as Controller;

class CRUDController extends Controller
{
    // ...
    /**
     * @param $id
     */
    public function cloneAction($id)
    {
        $object = $this->admin->getSubject();

        if (!$object) {
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
        }

        // Be careful, you may need to overload the __clone method of your object
        // to set its id to null !
        $clonedObject = clone $object;

        $clonedObject->setName($object->getName().' (Clone)');

        $this->admin->create($clonedObject);

        $this->addFlash('sonata_flash_success', 'Cloned successfully');

        return new RedirectResponse($this->admin->generateUrl('list'));

        // if you have a filtered list and want to keep your filters after the redirect
        // return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
    }
}

但是当我点击克隆时我显示了这个错误:

enter image description here

你能帮助我吗??

2 个答案:

答案 0 :(得分:2)

我觉得您忘记以正确的方式为此页面配置管理服务,请查看http://symfony.com/doc/current/bundles/SonataAdminBundle/cookbook/recipe_custom_action.html#register-the-admin-as-a-service

因为sonata默认使用SonataAdmin:CRUD控制器,如果你想覆盖控制器,你应该指定一个自定义控制器。

Element Should Be Visible

答案 1 :(得分:1)

您忘记为控制器配置路由。 Sonata Admin必须知道您的新动作才能为其生成路线。为此,您必须在管理类中配置configureRoutes方法:

class CarAdmin extends AbstractAdmin  // For Symfony version > 3.1
{

    // ...

    /**
     * @param RouteCollection $collection
     */
     protected function configureRoutes(RouteCollection $collection)
     {
         $collection->add('clone', $this->getRouterIdParameter().'/clone');
     }
}

正如您所看到的,CRUDController中路径的名称与动作的名称相匹配(但没有动作!)。 你有动作的名字:&#39; cloneAction&#39;所以路线的名称是&#34;克隆&#34;。