Symfony2:在 SonataAdmin 中覆盖 createAction() [英] Symfony2: Overriding createAction() in SonataAdmin

查看:22
本文介绍了Symfony2:在 SonataAdmin 中覆盖 createAction()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近几天我一直在疯狂地搜索,试图弄清楚(但没有成功)如何覆盖 SonataAdmin 操作以捕获会话用户名并将其保存在外键字段中.

I've been googling as crazy the last days trying to figure out (with no success) how override a SonataAdmin action to capture the session username and save it in the foreign key field.

AttachmentAdminController 类:

AttachmentAdminController class:

<?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(甚至整个类文件)忽略了,因为根本没有错误消息,但我不知道为什么.实际上,我不确定我是否从会话中获取用户名.

Seems to me as the actionController() is been ignored by SonataAdminBundle (and maybe the whole class file), because there's not error messages at all, but I don't know why. Actually, I'm not sure if I'm fetching the username from the session.

我真的需要一个关于这方面的好教程,但似乎我获得的任何有关这方面的信息在某些方面都已过时.顺便说一句,我使用的是 Symfony 2.0.16

I really need a good tutorial about this, but seems like any information I get about this is obsolete in some aspect. By the way, I'm using Symfony 2.0.16

推荐答案

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

Finally I got to the solution. I'm sure there are some others (like using event listeners, for example, that seems to be simpler), but right now it's the best I could find (it works, and that's what matters).

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

I was trying to override the createAction() based on examples that I found in another forum thread, but I was getting two records in the table instead of one only. The most important thing was overriding the WHOLE action method and put the custom code in it.

控制器:

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

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

I took the solution from the following sites:

(以及奏鸣曲项目文档)

(And the Sonata Project documentation)

这篇关于Symfony2:在 SonataAdmin 中覆盖 createAction()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆