我一直在谷歌搜索疯狂的最后几天试图找出(没有成功)如何覆盖SonataAdmin操作捕获会话用户名并将其保存在外键字段中。
AttachmentAdminController类:
<?php
namespace Application\Sonata\UserBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
#use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\UserBundle\Entity\User;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Bridge\Monolog\Logger;
use Mercury\CargoRecognitionBundle\Entity\Attachment;
class AttachmentAdminController extends Controller
{
/**
* (non-PHPdoc)
* @see Sonata\AdminBundle\Controller.CRUDController::createAction()
*/
public function createAction()
{
$result = parent::createAction();
if ($this->get('request')->getMethod() == 'POST')
{
$flash = $this->get('session')->getFlash('sonata_flash_success');
if (!empty($flash) && $flash == 'flash_create_success')
{
#$userManager = $this->container->get('fos_user.user_manager');
#$user = $this->container->get('context.user');
#$userManager = $session->get('username');
$user = $this->container->get('security.context')->getToken()->getUser()->getUsername();
$attachment = new Attachment();
$attachment->setPath('/tmp/image.jpg');
$attachment->setNotes('nothing interesting to say');
$attachment->getSystemUser($user);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($product);
$em->flush();
}
}
return $result;
}
}
服务附件:
mercury.cargo_recognition.admin.attachment:
class: Mercury\CargoRecognitionBundle\Admin\AttachmentAdmin
tags:
- { name: sonata.admin, manager_type: orm, group: General, label: Attachments }
arguments: [ null, Mercury\CargoRecognitionBundle\Entity\Attachment, "SonataAdminBundle:CRUD" ]
对我来说似乎是因为SonataAdminBundle(可能是整个类文件)忽略了actionController(),因为根本没有错误消息,但我不知道为什么。实际上,我不确定我是否从会话中获取用户名。
我真的需要一个关于此的好教程,但似乎我得到的任何信息在某些方面已经过时了。顺便说一下,我正在使用Symfony 2.0.16
答案 0 :(得分:8)
最后我得到了解决方案。我确定还有一些其他的(例如,使用事件监听器,似乎更简单),但是现在它是我能找到的最好的(它有效,这才是最重要的)。
我试图根据我在另一个论坛帖子中找到的示例来覆盖createAction()
,但我在表中获得了两条记录而不是一条记录。最重要的是覆盖WHOLE操作方法并将自定义代码放入其中。
<强>控制器强>:
<?php
namespace Mercury\CargoRecognitionBundle\Controller;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Bridge\Monolog\Logger;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Application\Sonata\UserBundle\Entity\User;
use Mercury\CargoRecognitionBundle\Entity\Attachment;
use Mercury\CargoRecognitionBundle\Entity\SystemUser;
use Mercury\CargoRecognitionBundle\Repository\SystemUserRepository;
class AttachmentAdminController extends Controller
{
/**
* Set the system user ID
*/
private function updateFields($object)
{
$userName = $this->container->get('security.context')
->getToken()
->getUser()
->getUsername();
$user = $this->getDoctrine()
->getRepository('ApplicationSonataUserBundle:User')
->findOneByUsername($userName);
$object->setSystemUser($user);
return $object;
}
/**
* (non-PHPdoc)
* @see Sonata\AdminBundle\Controller.CRUDController::createAction()
*/
public function createAction()
{
// the key used to lookup the template
$templateKey = 'edit';
if (false === $this->admin->isGranted('CREATE')) {
throw new AccessDeniedException();
}
$object = $this->admin->getNewInstance();
$object = $this->updateFields($object);
// custom method
$this->admin->setSubject($object);
$form = $this->admin->getForm();
$form->setData($object);
if ($this->get('request')->getMethod() == 'POST') {
$form->bindRequest($this->get('request'));
$isFormValid = $form->isValid();
// persist if the form was valid and if in preview mode the preview was approved
if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
$this->admin->create($object);
if ($this->isXmlHttpRequest()) {
return $this->renderJson(array(
'result' => 'ok',
'objectId' => $this->admin->getNormalizedIdentifier($object)
));
}
$this->get('session')->setFlash('sonata_flash_success','flash_create_success');
// redirect to edit mode
return $this->redirectTo($object);
}
// show an error message if the form failed validation
if (!$isFormValid) {
$this->get('session')->setFlash('sonata_flash_error', 'flash_create_error');
} elseif ($this->isPreviewRequested()) {
// pick the preview template if the form was valid and preview was requested
$templateKey = 'preview';
}
}
$view = $form->createView();
// set the theme for the current Admin Form
$this->get('twig')->getExtension('form')->setTheme($view, $this->admin->getFormTheme());
return $this->render($this->admin->getTemplate($templateKey), array(
'action' => 'create',
'form' => $view,
'object' => $object,
));
}
}
控制器服务:
mercury.cargo_recognition.admin.attachment:
class: Mercury\CargoRecognitionBundle\Admin\AttachmentAdmin
tags:
- { name: sonata.admin, manager_type: orm, group: General, label: Attachments }
arguments: [ null, Mercury\CargoRecognitionBundle\Entity\Attachment, "MercuryCargoRecognitionBundle:AttachmentAdmin" ]
我从以下网站获取了解决方案:
(和Sonata项目文件)
答案 1 :(得分:1)
使用您自己的逻辑仅覆盖 preCreate 挂钩可能很有用:
/**
* This method can be overloaded in your custom CRUD controller.
* It's called from createAction.
*
* @param mixed $object
*
* @return Response|null
*/
protected function preCreate(Request $request, $object)
{
}