使用CRUD控制器在sonata管理包中进行自定义操作

问题描述 投票:1回答:2

我想在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

你能帮助我吗 ..?

php symfony sonata-admin symfony-sonata sonata
2个回答
2
投票

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

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

#src/AppBundle/Resources/config/admin.yml

services:
    app.admin.car:
        class: AppBundle\Admin\CarAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: Demo, label: Car }
        arguments:
            - null
            - AppBundle\Entity\Car
            - AppBundle:CRUD #put it here

1
投票

您忘记为控制器配置Route。 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中的操作名称相匹配(但没有操作!)。你有行动的名称:'cloneAction'所以路线的名称是“克隆”。

© www.soinside.com 2019 - 2024. All rights reserved.