In recent days, I have been looking like crazy, trying to figure out (without success) how to redefine the SonataAdmin action to capture the session username and save it in the foreign key field.
AttachmentAdminController Class:
<?php
namespace Application\Sonata\UserBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as 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
{
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')
{
$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" ]
It seems to me that actionController () is ignored by the SonataAdminBundle (and possibly the entire class file), because there are no error messages at all, but I don’t know why. In fact, I'm not sure if I get the username from the session.
I really need a good tutorial about this, but it looks like any information I get about it is outdated in some aspect. By the way, I'm using Symfony 2.0.16
abiyi source
share