Symfony2: Overriding createAction() in SonataAdmin - php

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 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;
}
}
service attachment:
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" ]
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.
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).
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.
Controller:
<?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,
));
}
}
Service for the controller:
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:
Sonata-Users,
Symfony framework forums,
(And the Sonata Project documentation)

It might be useful to override only the preCreate hook with your own logic:
/**
* 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)
{
}

Related

Symfony: Dynamic route for multiple entities

Currently working with Symfony 5.2
I am trying to create a dynamic route for multiple enties which have mostly same properties (some still have other fields too, but all have the same default properties).
Example (minified)
Entity News:
- id, title, author
Entity Event:
- id, title, author
I am now trying to create a dynamic route to fetch News or Events from my the repository.
class ContentController extends AbstractController {
/**
* #Route("/{type}", name="get_content")
*/
public function get(string $type) { //type is the name of the entity e.g. 'news' or 'event'
//fetch from repo
$results = $this->getDoctrine()->getRepository(/* entity class */)->findAll();
}
}
I already came up with some ideas, but not sure if they are good practise.
1) use full namespace for the entity (how do I check if the class exists? error handling?)
$results = $this->getDoctrine()->getRepository('App\\Entity\\News')->findAll();
$results = $this->getDoctrine()->getRepository('App\\Entity\\' . ucfirst($type))->findAll();
2) provide a route for each entity and call a generic function (not exactly what I want because I have like 10+ entities for this)
class ContentController extends AbstractController {
/**
* #Route("/news", name="get_news")
*/
public function get_news() {
$results = getContent(News::class);
}
/**
* #Route("/event", name="get_event")
*/
public function get_event() {
$results = getContent(Event::class);
}
public function getContent($class) {
return $this->getDoctrine()->getRepository($class)->findAll();
}
}
Mabye some of you have better ideas/improvements and can help me out a bit.
You can define available for fetching entities manually.
class ContentController extends AbstractController
{
/**
* #Route("/{type}", name="get_content")
*/
public function get(string $type)
{ //type is the name of the entity e.g. 'news' or 'event'
//fetch from repo
$results = $this->getDoctrine()->getRepository($this->getEntityClassFromType($type))->findAll();
}
private function getEntityClassFromType(string $type): string
{
//define your entities manually
foreach ([News::class, Event::class] as $class) {
$parts = explode('\\', $class);
$entity = array_pop($parts);
if ($type === lcfirst($entity)) {
return $class;
}
}
throw new NotFoundHttpException();
}
}
Or check your entities dynamically using $entityManager->getMetadataFactory()->hasMetadataFor($className);

Batch actions with Sonata Admin Bundle on Symfony

I need to get data grid on the controller but it does not allow to enter parameters in the function. How you recover that information?
services:
admin.category:
class: AppBundle\Admin\CategoryAdmin
arguments: [~, AppBundle\Entity\Category, AppBundle:CRUDCategory, ~]
tags:
- { name: sonata.admin, manager_type: orm, group: "General", label: Categories }
This is the controller
<?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())
);
}
}
And this is the function getBatchActions
public function getBatchActions() {
$actions = parent::getBatchActions();
unset($actions['delete']);
$actions['inactive'] = array(
'label' => 'Disable category',
'ask_confirmation' => false
);
return $actions;
}
The error is
Catchable Fatal Error: Argument 2 passed to
AppBundle\Controller\CRUDCategoryController::batchActionInactive()
must be an instance of AppBundle\Controller\Request, none given
It is much easier, do it this way instead of getting the categories by your own:
/**
* #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()));
}
This has nothing to do with Sonata and everything to do with Symfony : you forgot the use statement for Request. The AppBundle\Controller\Request should have made you realize that ;)
EDIT: second error : action methods should end with **Action*
I've already solved.
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())
);
}

Custom Sonata admin batch action error

followed by batch action documentation in sonata admin's website, created this custom batch action called AnalayseController.php:
<?php
namespace Admin\Store\Receipt\ReceiptBundle\Controller;
use Sonata\AdminBundle\Controller\CRUDController as BaseController;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class AnalyseController extends BaseController
{
/**
* #param ProxyQueryInterface $selectedModelQuery
* #param Request $request
*
* #return RedirectResponse
*/
public function batchActionAnalyse(ProxyQueryInterface $selectedModelQuery, Request $request = null)
{
$request = $this->get('request');
$modelManager = $this->admin->getModelManager();
$target = $modelManager->find($this->admin->getClass(), $request->get('targetId'));
if ($target === null){
$this->addFlash('sonata_flash_info', 'No target!');
return new RedirectResponse(
$this->admin->generateUrl('list', $this->admin->getFilterParameters())
);
}
$selectedModels = $selectedModelQuery->execute();
$this->addFlash('sonata_flash_success', 'Done');
return new RedirectResponse(
$this->admin->generateUrl('list', $this->admin->getFilterParameters())
);
}
}
but I'm getting this error: Catchable Fatal Error: Argument 1 passed to Admin\Store\Receipt\ReceiptBundle\Controller\AnalyseController::batchActionAnalyse() must implement interface Sonata\AdminBundle\Datagrid\ProxyQueryInterface, string given, called in /home/aien/Web/Mr Alef/MRA_Dev/app/cache/dev/appDevDebugProjectContainer.php on line 852 and defined.
looked everywhere, but couldn't find any solution!
Ok, I've fixed the issue just by changing serives.yml calls first argument to setTranslationDomain
admin_store_receipt_receipt.admin.analyse:
class: Admin\Store\Receipt\ReceiptBundle\Admin\ReceiptAdmin
tags:
- { name: sonata.admin, manager_type: orm, group: admin, label: Receipt }
arguments:
- ~
- Admin\Store\Receipt\ReceiptBundle\Entity\Receipt
- AdminStoreReceiptReceiptBundle:Analyse
calls:
- [ setTranslationDomain , [AdminStoreReceiptReceiptBundle]]

Access Container or securityContext or EntityManager from MenuBuilder through RequestVoter

I found this piece of code shared in a Gist (somewhere I lost the link) and I needed something like that so I started to use in my application but I have not yet fully understood and therefore I am having some problems.
I'm trying to create dynamic menus with KnpMenuBundle and dynamic means, at some point I must verify access permissions via database and would be ideal if I could read the routes from controllers but this is another task, perhaps creating an annotation I can do it but I will open another topic when that time comes.
Right now I need to access the SecurityContext to check if the user is logged or not but not know how.
I'm render the menu though RequestVoter (I think) and this is the code:
namespace PlantillaBundle\Menu;
use Knp\Menu\ItemInterface;
use Knp\Menu\Matcher\Voter\VoterInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
class RequestVoter implements VoterInterface {
private $container;
private $securityContext;
public function __construct(ContainerInterface $container, SecurityContextInterface $securityContext)
{
$this->container = $container;
$this->securityContext = $securityContext;
}
public function matchItem(ItemInterface $item)
{
if ($item->getUri() === $this->container->get('request')->getRequestUri())
{
// URL's completely match
return true;
}
else if ($item->getUri() !== $this->container->get('request')->getBaseUrl() . '/' && (substr($this->container->get('request')->getRequestUri(), 0, strlen($item->getUri())) === $item->getUri()))
{
// URL isn't just "/" and the first part of the URL match
return true;
}
return null;
}
}
All the code related to securityContext was added by me in a attempt to work with it from the menuBuilder. Now this is the code where I'm making the menu:
namespace PlantillaBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class MenuBuilder extends ContainerAware {
public function mainMenu(FactoryInterface $factory, array $options)
{
// and here is where I need to access securityContext
// and in the near future EntityManger
$user = $this->securityContext->getToken()->getUser();
$logged_in = $this->securityContext->isGranted('IS_AUTHENTICATED_FULLY');
$menu = $factory->createItem('root');
$menu->setChildrenAttribute('class', 'nav');
if ($logged_in)
{
$menu->addChild('Home', array('route' => 'home'))->setAttribute('icon', 'fa fa-list');
}
else
{
$menu->addChild('Some Menu');
}
return $menu;
}
}
But this is complete wrong since I'm not passing securityContext to the method and I don't know how to and I'm getting this error:
An exception has been thrown during the rendering of a template
("Notice: Undefined property:
PlantillaBundle\Menu\MenuBuilder::$securityContext in
/var/www/html/src/PlantillaBundle/Menu/MenuBuilder.php line 12") in
/var/www/html/src/PlantillaBundle/Resources/views/menu.html.twig at
line 2.
The voter is defined in services.yml as follow:
plantilla.menu.voter.request:
class: PlantillaBundle\Menu\RequestVoter
arguments:
- #service_container
- #security.context
tags:
- { name: knp_menu.voter }
So, how I inject securityContext (I'll not ask for EntityManager since I asume will be the same procedure) and access it from the menuBuilder?
Update: refactorizing code
So, following #Cerad suggestion I made this changes:
services.yml
services:
plantilla.menu_builder:
class: PlantillaBundle\Menu\MenuBuilder
arguments: ["#knp_menu.factory", "#security.context"]
plantilla.frontend_menu_builder:
class: Knp\Menu\MenuItem # the service definition requires setting the class
factory_service: plantilla.menu_builder
factory_method: createMainMenu
arguments: ["#request_stack"]
tags:
- { name: knp_menu.menu, alias: frontend_menu }
MenuBuilder.php
namespace PlantillaBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class MenuBuilder {
/**
* #var Symfony\Component\Form\FormFactory $factory
*/
private $factory;
/**
* #var Symfony\Component\Security\Core\SecurityContext $securityContext
*/
private $securityContext;
/**
* #param FactoryInterface $factory
*/
public function __construct(FactoryInterface $factory, $securityContext)
{
$this->factory = $factory;
$this->securityContext = $securityContext;
}
public function createMainMenu(RequestStack $request)
{
$user = $this->securityContext->getToken()->getUser();
$logged_in = $this->securityContext->isGranted('IS_AUTHENTICATED_FULLY');
$menu = $this->factory->createItem('root');
$menu->setChildrenAttribute('class', 'nav');
if ($logged_in)
{
$menu->addChild('Home', array('route' => 'home'))->setAttribute('icon', 'fa fa-list');
}
else
{
$menu->addChild('Some Menu');
}
return $menu;
}
}
Abd ib my template just render the menu {{ knp_menu_render('frontend_menu') }} but now I loose the FontAwesome part and before it works, why?
Your menu builder is ContainerAware, so I guess that in it you should access the SecurityContext via $this->getContainer()->get('security.context').
And you haven't supplied any use cases for the voter class, so I'm guessing you're not using the matchItem method.
You should definitely try to restructure your services so that the dependencies are obvious.
Per your comment request, here is what your menu builder might look like:
namespace PlantillaBundle\Menu;
use Knp\Menu\FactoryInterface;
class MenuBuilder {
protected $securityContext;
public function __construct($securityContext)
{
$this->securityContext = $securityContext;
}
public function mainMenu(FactoryInterface $factory, array $options)
{
// and here is where I need to access securityContext
// and in the near future EntityManger
$user = $this->securityContext->getToken()->getUser();
...
// services.yml
plantilla.menu.builder:
class: PlantillaBundle\Menu\MenuBuilder
arguments:
- '#security.context'
// controller
$menuBuilder = $this->container->get('plantilla.menu.builder');
Notice that there is no need to make the builder container aware since you only need the security context service. You can of course inject the entity manager as well.
================================
With respect to the voter stuff, right now you are only checking to see if a user is logged in. So no real need for voters. But suppose that certain users (administrators etc) had access to additional menu items. You can move all the security checking logic to the voter. Your menu builder code might then look like:
if ($this->securityContext->isGranted('view','homeMenuItem')
{
$menu->addChild('Home', array('route' ...
In other words, you can get finer controller over who gets what menu item.
But get your MenuBuilder working first then add the voter stuff if needed.

Symfony 2.0 getting service inside entity

Im seraching over and cannot find answer.
I have database role model in my application. User can have a role but this role must be stored into database.
But then user needs to have default role added from database. So i created a service:
<?php
namespace Alef\UserBundle\Service;
use Alef\UserBundle\Entity\Role;
/**
* Description of RoleService
*
* #author oracle
*/
class RoleService {
const ENTITY_NAME = 'AlefUserBundle:Role';
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function findAll()
{
return $this->em->getRepository(self::ENTITY_NAME)->findAll();
}
public function create(User $user)
{
// possibly validation here
$this->em->persist($user);
$this->em->flush($user);
}
public function addRole($name, $role) {
if (($newrole = findRoleByRole($role)) != null)
return $newrole;
if (($newrole = findRoleByName($name)) != null)
return $newrole;
//there is no existing role
$newrole = new Role();
$newrole->setName($name);
$newrole->setRole($role);
$em->persist($newrole);
$em->flush();
return $newrole;
}
public function getRoleByName($name) {
return $this->em->getRepository(self::ENTITY_NAME)->findBy(array('name' => $name));
}
public function getRoleByRole($role) {
return $this->em->getRepository(self::ENTITY_NAME)->findBy(array('role' => $role));
}
}
my services.yml is:
alef.role_service:
class: Alef\UserBundle\Service\RoleService
arguments: [%doctrine.orm.entity_manager%]
And now I want to use it in two places:
UserController and User entity. How can i get them inside entity?
As for controller i think i just need to:
$this->get('alef.role_service');
But how to get service inside entity?
You don't. This is a very common question. Entities should only know about other entities and not about the entity manager or other high level services. It can be a bit of a challenge to make the transition to this way of developing but it's usually worth it.
What you want to do is to load the role when you load the user. Typically you will end up with a UserProvider which does this sort of thing. Have you read through the sections on security? That should be your starting point:
http://symfony.com/doc/current/book/security.html
The reason why it's so difficult to get services into entities in the first place is that Symfony was explicitly designed with the intent that services should never be used inside entities. Therefore, the best practice answer is to redesign your application to not need to use services in entities.
However, I have found there is a way to do it that does not involve messing with the global kernel.
Doctrine entities have lifeCycle events which you can hook an event listener to, see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#lifecycle-events For the sake of the example, I'll use postLoad, which triggers soon after the Entity is created.
EventListeners can be made as services which you inject other services into.
Add to app/config/config.yml:
services:
example.listener:
class: Alef\UserBundle\EventListener\ExampleListener
arguments:
- '#alef.role_service'
tags:
- { name: doctrine.event_listener, event: postLoad }
Add to your Entity:
use Alef\UserBundle\Service\RoleService;
private $roleService;
public function setRoleService(RoleService $roleService) {
$this->roleService = $roleService;
}
And add the new EventListener:
namespace Alef\UserBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Alef\UserBundle\Service\RoleService;
class ExampleListener
{
private $roleService;
public function __construct(RoleService $roleService) {
$this->roleService = $roleService;
}
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if(method_exists($entity, 'setRoleService')) {
$entity->setRoleService($this->roleService);
}
}
}
Just keep in mind this solution comes with the caveat that this is still the quick and dirty way, and really you should consider redesigning your application the proper way.
Thanks to Kai's answer above which answer to the question, but it's not compatible with symfony 5.x .
It's good to precise it's a bad practice, but required in some special case like legacy code or a bad DB design (as a temporary solution before schema migration)
As in my case, I use this code with a mailer and translator, which introduce an issue with the private property if Symfony >= 5.3 , so here the solution for recent version of symfony:
in config/services.yaml:
services:
Alef\UserBundle\EventListener\ExampleListener:
tags:
- { name: doctrine.event_listener, event: postLoad }
ExampleListener:
namespace Alef\UserBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Alef\UserBundle\Entity\Role;
class ExampleListener
{
public function postLoad(LifecycleEventArgs $postLoad): void
{
$entity = $postLoad->getEntity();
if ($entity instanceof User) {
$repository = ;
$entity->roleRepository(
$postLoad->getEntityManager()->getRepository(Role::class)
);
}
}
}
And in your Entity (or in a trait if you use it in more than one entity):
use Alef\UserBundle\Service\RoleService;
/** #internal bridge for legacy schema */
public function roleRepository(?RoleRepository $repository = null) {
static $roleRepository;
if (null !== $repository) {
$roleRepository = $repository;
}
return $roleRepository;
}
public function getRoleByName($name) {
return $this->roleRepository()->findBy(array('name' => $name));
}

Categories