Skip to content

Commit

Permalink
Add 'setPreferredLocaleActions' with custom route pattern and params
Browse files Browse the repository at this point in the history
  • Loading branch information
DumitracheAdrian committed Oct 3, 2024
1 parent 9e8a519 commit d3cf270
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
28 changes: 28 additions & 0 deletions app/src/Controller/Admin/SetPreferredLocaleAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Entity\User;
use Draw\Bundle\SonataExtraBundle\ActionableAdmin\ObjectActionExecutioner;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;

#[AsController]
class SetPreferredLocaleAction
{
public function __invoke(
Request $request,
ObjectActionExecutioner $objectActionExecutioner,
): Response {
return $objectActionExecutioner->execute(
static function (User $user) use ($request, $objectActionExecutioner): void {
$user->setPreferredLocale($request->get('_locale') ?? 'en');

$objectActionExecutioner->getAdmin()->update($user);
}
);
}
}
19 changes: 18 additions & 1 deletion app/src/Sonata/Admin/UserAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Controller\Admin\AddRolesAminAction;
use App\Controller\Admin\MakeAdminAction;
use App\Controller\Admin\SetPreferredLocaleAction;
use App\Entity\Tag;
use App\Entity\User;
use Draw\Bundle\SonataExtraBundle\ActionableAdmin\ActionableAdminInterface;
Expand Down Expand Up @@ -108,6 +109,7 @@ protected function configureShowFields(ShowMapper $show): void
->add('childObject2')
->add('email')
->add('dateOfBirth')
->add('preferredLocale')
->add('roles', 'json')
->add('rolesList', 'list')
->add('static', 'static', ['virtual_field' => true, 'value' => 'Static value'])
Expand Down Expand Up @@ -220,6 +222,21 @@ public function getActions(): array
'addRoles' => (new AdminAction('addRoles', true))
->setController(AddRolesAminAction::class)
->setBatchController(AddRolesAminAction::class),
];
] + iterator_to_array($this->prepareSetPreferredLocaleActions());
}

private function prepareSetPreferredLocaleActions(): iterable
{
foreach (['en', 'fr'] as $locale) {
yield $name = \sprintf('setPreferredLocale%s', ucfirst($locale)) => (new AdminAction($name, true))
->setLabel(strtoupper($locale))
->setIcon('fa fa-language')
->setController(SetPreferredLocaleAction::class)
->setRoutePattern(
\sprintf('%s/preferred-locale/{_locale}', $this->getRouterIdParameter())
)
->addRouteParam('_locale', $locale)
;
}
}
}

0 comments on commit d3cf270

Please sign in to comment.