Child Admin route is not being generated - Sonata Admin Bundle - symfony

I'm trying to set up an Admin as a child of an other Admin in Sonata Admin Bundle.
I have 2 Admin classes:
CategoryAdmin
This class contains the following method
protected function configureSideMenu(MenuItemInterface $menu, $action, AdminInterface $childAdmin = null)
{
$id = $this->getRequest()->get('id');
$menu->addChild(
$this->trans('Projects'),
array('uri' => $this->getChild('sonata.admin.project')->generateUrl('list', array('id' => $id)))
);
}
ProjectAdmin
This class contains protected $parentAssociationMapping = 'category';
category is the property in the model class representing the ManyToOne association.
I added the following lines to my service configuration for CategoryAdmin
calls:
- [ addChild, ["#sonata.admin.project"]]
The routes for the child Admin are not being generated with this configuration. The link in the SideMenu (top menu) points to /admin/project/list?childId=1&id=1
Here is the output of the children of CategoryAdmin with dump()
array:1 [▼
"sonata.admin.project" => ProjectAdmin {#406 ▶}
]
This means that the configuration for my child admin seems to be correct. I have no idea, why the routes for the child admin are not being generated.
I hope somebody can give me a hint, what the problem could be.

Note for next gen sonata coders:
If your route is not being generated, first check you didn't do:
protected function configureRoutes(RouteCollection $collection)
{
//clear all routes except given !!!
$collection->clearExcept(array('list', 'show'));
}
It costs me two days...

Do you have the $baseRouteName and $baseRoutePattern overriden in your admin class ?
If you do, Sonata will generate both child and parent routes with the same name resulting in the parent routes overriding the child ones.

I bumped into this issue while solving the problem for myself and decided to share the solution, which costed me several debugging hours...
The only way to generate a proper uri in this case is to use low-level routeGenerator which doesn't make any sonata suggestions, made inside generateMenuUrl method.
First you have to debug the routes, you have in your app (including autogenerated by sonata).
php bin/console debug:router
For example I have 3 nesting levels
hall -> seats scheme -> sector
And my routes are following:
adminHall_list ANY ANY ANY /admin/hall/list
adminHall_create ANY ANY ANY /admin/hall/create
adminHall_edit ANY ANY ANY /admin/hall/{id}/edit
adminHall_delete ANY ANY ANY /admin/hall/{id}/delete
adminHall_adminScheme_list ANY ANY ANY /admin/hall/{id}/scheme/list
adminHall_adminScheme_create ANY ANY ANY /admin/hall/{id}/scheme/create
adminHall_adminScheme_edit ANY ANY ANY /admin/hall/{id}/scheme/{childId}/edit
adminHall_adminScheme_delete ANY ANY ANY /admin/hall/{id}/scheme/{childId}/delete
adminHall_adminScheme_adminSector_list ANY ANY ANY /admin/hall/{id}/scheme/{childId}/sector/list
adminHall_adminScheme_adminSector_create ANY ANY ANY /admin/hall/{id}/scheme/{childId}/sector/create
adminHall_adminScheme_adminSector_edit ANY ANY ANY /admin/hall/{id}/scheme/{childId}/sector/{childChildId}/edit
adminHall_adminScheme_adminSector_delete ANY ANY ANY /admin/hall/{id}/scheme/{childId}/sector/{childChildId}/delete
In admin classes baseRouteName and baseRoutePattern has been overridden.
// HallSchemeAdmin.php
$this->baseRouteName = 'adminScheme';
$this->baseRoutePattern = 'scheme';
To generate a most deep listing url:
$url = $admin->getRouteGenerator()->generate('adminHall_adminScheme_adminSector_list', [
'id' => $admin->getRequest()->get('id'),
'childId' => 555, // put required id
]);
It will produce the url like this:
/admin/hall/495/scheme/555/sector/list
If you need edit url, you have to provide childChildId param too:
$url = $admin->getRouteGenerator()->generate('adminHall_adminScheme_adminSector_edit', [
'id' => $admin->getRequest()->get('id'),
'childId' => 555,
'childChildId' => 12345
]);
The result is:
/admin/hall/495/scheme/555/sector/12345/edit

Related

How to configure a Translatable Entity in EasyAdmin?

I'm using Translatable and EasyAdmin in a Symfony 5 project and I have configured 2 languages.
The issue is I need to be able to edit the different languages of a record in EasyAdmin, I have checked the docs of Translatable, EasyAdmin and Symfony, There is very little information about how to integrate database translations into EasyAdmin.
Therefore, I'm a bit stuck in terms of code, I have tried configuring setTranslationParameters() inside the entity CRUD controller and changing some configuration in the DashboardController however, I don't think this is the right approach.
Any suggestions of how to solve this issue?
Thank you for your effort and time.
as of writing, this feature doesn't exist in EasyAdmin, please see the link to the answer to the issue on Github.
https://github.com/EasyCorp/EasyAdminBundle/issues/4982
However, a work around is possible with a different package:
remove doctrine-extensions/DoctrineExtensions and then install KnpLabs/DoctrineBehaviors
install a2lix/translation-form-bundle
Create a translation field:
<?php
declare(strict_types=1);
namespace App\Controller\Admin\Field;
use A2lix\TranslationFormBundle\Form\Type\TranslationsType;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\FieldTrait;
final class TranslationField implements FieldInterface
{
use FieldTrait;
public static function new(string $propertyName, ?string $label = null, array $fieldsConfig = []): self
{
return (new self())
->setProperty($propertyName)
->setLabel($label)
->setFormType(TranslationsType::class)
->setFormTypeOptions([
'default_locale' => 'cz',
'fields' => $fieldsConfig,
]);
}
}
Use the TranslationField inside your admin CRUD controller:
public function configureFields(string $pageName): iterable
{
return [
TextField::new('title', 'title')->hideOnForm(),
TranslationField::new('translations', 'translations', [
'title' => [
'field_type' => TextType::class,
'required' => true,
]
// add more translatable properties into the array
])->setRequired(true)
->hideOnIndex()
];
}

Altering a dynamic route in Drupal 8 with RouteSubscriber

I have a web-app made in Drupal 8, and I have some routing problems. Users will login using an external service, and after login they are sent to the path /user/{user}, where {user} is their user id. I want to change this behaviour and send them to a page /dashboard. Not having access to what the external service routing is doing, I need to reroute /user/{user} to /dashboard. It seems like the drupal 8 redirect module could solve the problem, but I am not too keen on using an external module just for this simple task.
Because of this, I tried to change the route with drupal's RouteSubscriber and alterRoutes method. So I made my RouteSubscriber class in my module called "module" like this:
class RouteSubscriber extends RouteSubscriberBase {
protected function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('user.page')) {
$route->setDefaults(array(
'_controller' => '\Drupal\module\Controller\Dashboard::content',
));
}
if ($route = $collection->get('entity.user.canonical')) {
$route->setDefaults(array(
'_controller' => '\Drupal\module\Controller\Dashboard::content',
));
}
}
}
The route user.page has path /user, and the path entity.user.canonical is the route I'm interested in, which has path /user/{user}, where {user} is again a path parameter. When I go to the page /user, the dashboard is displayed as expected, but going to for example /user/123 does not show the dashboard, but seems display what the route originally did. Just to test whether it was impossible to alter this route, I tried to set all routes to have display the dashboard by inserting the following code into RouteSubscriber:
foreach ($collection->all() as $route) {
$route->setDefaults(array(
'_controller' => '\Drupal\module\Controller\Dashboard::content',
'pid' => '',
'uid' => '',
'modifier' => '',
'display' => '',
));
}
The junk pid, uid, modifier and display are just defaults to different routes path parameters so the code will run. This makes the page /user/123 correctly display the dashboard! However, I do get the following error message at the bottom of the screen:
The website encountered an unexpected error. Please try again later.
Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("filter") to generate a URL for route "devel.configs_list". in Drupal\Core\Routing\UrlGenerator->doGenerate() (line 182 of core/lib/Drupal/Core/Routing/UrlGenerator.php).
So, what am I doing wrong here? Can what I want be done, or should I do something different to achieve what I want? Also, feel free to ask for more code if needed!

OroPlatform: add custom field on core Entity

I'm currently working on an OroPlatform project and I need to add a custom field on the BusinessUnit core entity.
I have read the Oro documentation section about the way to extend core entities : https://doc.oroinc.com/backend/entities/extend-entities/#id1
<?php
namespace MyBundle\Bundle\AppBundle\Migrations\Schema\v1_0;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class AddColumnsToBusinessUnit implements Migration
{
public function up(Schema $schema, QueryBag $queries)
{
$table = $schema->getTable('oro_business_unit');
$table->addColumn('siret', 'string', [
'oro_options' => [
'extend' => ['owner' => ExtendScope::OWNER_CUSTOM],
'entity' => ['label' => 'siret'],
],
]);
}
}
When I run the command symfony console oro:migration:load --force, it works and the migration is applied to my database.
Now, I want a required field. I have seen the instruction 'notnull' => true to setup a non nullable field on the database.
Everything works well, but my field hasn't any JavaScript validation on the organization/business_unit/create route. Any ideas ?
You can validate the new field by extending the validation metadata that is already defined for the core entity you are extending.
To do this, please follow the official Symfony documentation and use the YML format:
https://symfony.com/doc/4.4/validation.html#constraint-configuration
The constraint that you can use for the field is "not blank."
Here is an example:
# src/<YourBundlePath>/Resources/config/validation.yml
Oro\Bundle\OrganizationBundle\Entity\BusinessUnit:
properties:
siret:
- NotBlank: ~

How to add item_permission on delete action in easyadmin?

I use EasyadminBundle for the Backend of a Symfony application.
Two type of users have access to the back-end and I'd like to keep the right to delete to a small number of persons granted with ROLE_ADMIN.
I'd like to use item_permission parameter as for the other actions (such as show or list) :
Lieu:
class: App\Entity\Lieu
list:
item_permission: ROLE_ENCADRANT
delete:
item_permission: ROLE_ADMIN
But it's not working and I can still delete user when I'm logged with ROLE_ENCADRANT. Is there another solution ?
I currently accomplish it with:
Lieu:
class: App\Entity\Lieu
list:
item_permission: ROLE_ENCADRANT
action: ['-delete']
help: "the delete button is accessible in <b>Edit</b> view"
form:
item_permission: ROLE_ADMIN
I'm just looking for a 100% configuration solution, more elegant than mine.
Take a look at adding an action in the docs. The action can be tied to a route, which allows specifying what role may perform the action. The downside is that the list view button is present regardless of role. You can add a flash message to advise the user whether they have permission.
Here's an example from a project. Not quite what you're looking for but may get you started:
easyadmin.yaml:
Admin:
class: App\Entity\Admin
disabled_actions: ['new', 'edit']
list:
actions:
-
name: 'admin_enabler'
type: 'route'
label: 'Enable/Disable'
controller:
/**
* #Route("/enabler", name = "admin_enabler")
*/
public function enabler(Request $request)
{
$em = $this->getDoctrine()->getManager();
$id = $request->query->get('id');
$admin = $em->getRepository(Admin::class)->find($id);
$enabled = $admin->isEnabled();
if (!$admin->isActivator() && !$admin->hasRole('ROLE_SUPER_ADMIN')) {
$admin->setEnabled(!$enabled);
$em->persist($admin);
$em->flush();
} else {
$this->addFlash('danger', $admin->getFullName() . ' cannot be disabled');
}
return $this->redirectToRoute('easyadmin', array(
'action' => 'list',
'entity' => $request->query->get('entity'),
));
}

Access Service from Controller and/or Twig template

Disclaimer: I'm slowly starting to get into Symfony and still have some problems understanding how the architecture works.
Currently I set up different Bundles (Services, right?) that should deliver different output for different routes. So far I got around adding a simple Twig template that loads stylesheets and scripts via Assetics and Twig-blocks. Now I added another Bundle that queries data via Buzz from a remote location, which worked fine as a standalone script, but I don't get around printing output in a Twig template.
The architecture of the original script is like the following (names made more generic):
Vendors - abstract class that serves as base for all remote request Bundles.
ServiceABC - abstract class that extends Vendors and defines Error handling and output preparation for the ABC service.
ClientXYZ - final class that extends Service_ABC, defines output parsing and normalization of the returned data.
This Bundle got a services.yml file:
# ~/MyApp/Bundle/ServiceABCBundle/Resources/config/services.yml
parameters:
service_abc_manager.class: MyApp\Bundle\ServiceABCBundle\Models\Service_ABC
location_manager.class: MyApp\Bundle\ServiceABCBundle\Models\Clients\ClientLocation
monitor_manager.class: MyApp\Bundle\ServiceABCBundle\Models\Clients\ClientMonitor
services:
service_abc_manager:
abstract: true
location_manager:
class: %location_manager.class%
parent: service_abc_manager
monitor_manager:
class: %monitor_manager.class%
parent: service_abc_manager
Names changed for easier reference - Typos by accident possible.
Now my problem/question is, that I don't really get behind the Symfony2 concept of how to get the output into the template.
namespace MyApp\Bundle\ServiceABCBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use MyApp\Bundle\ServiceABCBundle\Models\Clients\ClientLocation;
class DefaultController extends Controller
{
public function indexAction()
{
$services = array();
$services[] = $this->container->has('service_abc_manager');
$services[] = $this->container->has('location_manager');
$services[] = $this->container->has('client_location');
$services[] = $this->container->has('ClientLocation');
var_dump( $services );
$client = new ClientLocation();
var_dump( $client );
$response = $this->render(
'Service_ABC:Default:index.html.twig'
);
# $response->setCharset( 'utf-8' );
# $response->headers->set( 'Content-Type', 'text/html' );
return $response;
}
}
The output of the first array() named $services is always false and the $client = new ClientLocation(); throws an Exception that the class name wasn't found.
How can I access those Services/Bundle(parts)/Classes? And how would I render the output to a template?
Update
After I added the complete tree definition to Configuration()->getConfigTreeBuilder(), I'm able to see the definitions in the CLI:
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root( 'myapp_service_abc' );
$rootNode
->children()
->scalarNode('service_abc_manager')->end()
->scalarNode('location_manager')->end()
->scalarNode('monitor_manager')->end()
->end()
;
return $treeBuilder;
}
}
The CLI command php app/console config:dump-reference myapp_service_abc now gives me the following output:
myapp_service_abc:
service_abc_manager: ~
location_manager: ~
monitor_manager: ~
I can as well see that the config data was loaded, when I var_dump( $loader ); inside MyAppServiceABCExtension right after $loader->load( 'services.yml' ); was called.
The output is the following:
object(Symfony\Component\DependencyInjection\Loader\YamlFileLoader)
protected 'container' =>
object(Symfony\Component\DependencyInjection\ContainerBuilder)
private 'definitions' =>
array
'service_abc_manager' =>
object(Symfony\Component\DependencyInjection\Definition)
'location_manager' =>
object(Symfony\Component\DependencyInjection\DefinitionDecorator)
private 'parent' => string 'service_abc_manager'
// etc.
The problem itself remains: There's still a FALSE return value inside DefaultController()->indexAction() when I var_dump( $this->container->has( 'service_abc_manager' );. I as well tried var_dump( $this->container->has( 'location_manager' ); and var_dump( $this->container->has( 'myapp.service_abc_manager' ); with the same result.
You should not call your services from the twig file, but from the controller.
The role of the controller is to :
validate your forms if there were a form posted
call your services to get some stuffs to display in a view
initialize forms if there is a form to display
return a Response that typically contains a rendered twig view
Do not call your services using something like $client = new ClientLocation();, but call it using the service container. This will allow you to take the whole power of the dependancy injection offered by Symfony2.
Your controller will look like :
<?php
namespace MyApp\Bundle\ServiceABCBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
$locationService = $this->container->get('location_manager');
$someStuffs = $locationService->someMethod();
$response = $this->render(
'ServiceABCBundle:Default:index.html.twig', array('stuffs' => $someStuffs)
);
return $response;
}
}
From your twig file, you'll be able to use the stuffs variable :
{{ stuffs }} if your variable is a terminal ( a string, a number... )
{{ stuffs.attribute }} if your variable is an object or an array
About your services file, I am a bit confused, because your architecture does not look to be the standard Symfony2's one :
# ~/MyApp/Bundle/ServiceABCBundle/Resources/config/services.yml
Why your services.yml file isn't in the src/MyApp/SomethingBundle/Resources/config/ directory?
If you didn't already read it, I suggest you to have a look to the Symfony2 : The Big Picture documentation, which is the best way to start with Symfony2.

Resources