[英]Batch actions with Sonata Admin Bundle on Symfony
我需要在控制器上獲取數據網格,但不允許在函數中輸入參數。 你如何恢復這些信息?
services:
admin.category:
class: AppBundle\Admin\CategoryAdmin
arguments: [~, AppBundle\Entity\Category, AppBundle:CRUDCategory, ~]
tags:
- { name: sonata.admin, manager_type: orm, group: "General", label: Categories }
這是控制器
<?php
namespace AppBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as SonataController;
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery as ProxyQueryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
class CRUDCategoryController extends SonataController {
/**
* @param ProxyQueryInterface $selectedModelQuery
* @param Request $request
*
* @return RedirectResponse
*/
public function batchActionInactive(ProxyQueryInterface $selectedModelQuery, Request $request) {
$em = $this->getDoctrine()->getManager();
$category = $em->getRepository('AppBundle:Category')->find($request->getId());
$category->setState('INACTIVE');
$em->flush();
return new RedirectResponse(
$this->admin->generateUrl('list', $this->admin->getFilterParameters())
);
}
}
這是函數getBatchActions
public function getBatchActions() {
$actions = parent::getBatchActions();
unset($actions['delete']);
$actions['inactive'] = array(
'label' => 'Disable category',
'ask_confirmation' => false
);
return $actions;
}
錯誤是
可捕獲的致命錯誤:傳遞給AppBundle \\ Controller \\ CRUDCategoryController :: batchActionInactive()的參數2必須是AppBundle \\ Controller \\ Request的實例,沒有給出
這樣做更容易,而不是通過自己的方式獲取類別:
/**
* @param ProxyQueryInterface $selectedModelQuery
*
* @return RedirectResponse
*/
public function batchActionInactive(ProxyQueryInterface $selectedModelQuery)
{
$selectedCategories = $selectedModelQuery->execute();
try {
/** @var Category $category */
foreach ($selectedCategories as $category) {
$category->setState('INACTIVE');
$this->admin->update($category);
}
} catch (\Exception $e) {
$this->addFlash(
'sonata_flash_error',
'Could not mark Categories "INACTIVE"'
);
$this->get('logger')->error($e->getMessage());
return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
}
$this->addFlash(
'sonata_flash_success',
'Categories were marked as "INACTIVE"'
);
return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
}
這與Sonata無關,與Symfony有關:你忘記了Request
的使用聲明。 AppBundle\\Controller\\Request
應該讓你意識到;)
編輯:第二個錯誤:動作方法應以**動作*結束
我已經解決了。
public function batchActionInactive(ProxyQueryInterface $selectedModelQuery) {
$em = $this->getDoctrine()->getManager();
$request = $this->getRequest();
$ids = $request->request->get('idx');
foreach ($ids as $id) {
$category = $em->getRepository('AppBundle:Category')->find($id);
$category->setState('INACTIVE');
$em->flush();
}
return new RedirectResponse(
$this->admin->generateUrl('list', $this->admin->getFilterParameters())
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.