7

在过去的几天里,我一直在疯狂地搜索(但没有成功)如何覆盖 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" ]

在我看来,actionController() 被 SonataAdminBundle (可能还有整个类文件)忽略了,因为根本没有错误消息,但我不知道为什么。实际上,我不确定我是否从会话中获取用户名。

我真的需要一个很好的教程,但似乎我得到的任何信息在某些方面都是过时的。顺便说一句,我使用的是 Symfony 2.0.16

4

2 回答 2

9

最后我得到了解决方案。我敢肯定还有其他一些(例如使用事件侦听器,这似乎更简单),但现在这是我能找到的最好的(它有效,这很重要)。

我试图覆盖createAction()我在另一个论坛线程中找到的基于示例,但我在表中得到了两条记录,而不是只有一条。最重要的是覆盖整个操作方法并将自定义代码放入其中。

控制器

<?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" ]

我从以下站点获取了解决方案:

(以及奏鸣曲项目文档)

于 2012-08-15T21:04:43.690 回答
2

使用您自己的逻辑仅覆盖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)
{
}
于 2018-05-15T12:32:12.420 回答