我想在Sonata管理包中创建自定义页面树枝(例如克隆):
我用这个教程:
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()));
}
}
但当我点击克隆时,我显示此错误:
你能帮助我吗 ..?
我觉得您忘记以正确的方式为此页面配置管理服务,请检查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
您忘记为控制器配置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'所以路线的名称是“克隆”。