Symfony Omines DataTables添加跳转用户详情页操作按钮实现方法
Hey there! Let's get that action button set up so you can jump to the user's page directly from your DataTable. Here's exactly how to modify your code:
Step 1: Update the Controller to Use a Template Column
Instead of using TextColumn for your actions, switch to TemplateColumn—this lets you render custom HTML (like a button) for that column. Here's your modified controller code:
use Omines\DataTablesBundle\Column\TemplateColumn; public function index(Request $request, UserRepository $repo) { $table = $this->createDataTable() ->add('login', TextColumn::class, ['label' => 'Login']) ->add('name', TextColumn::class, ['label' => 'Nom']) ->add('school', TextColumn::class, ['label' => 'Ecole']) ->add('region', TextColumn::class, ['label' => 'Région']) ->add('limitDate', TextColumn::class, ['label' => 'Date Limite']) ->add('status', TextColumn::class, ['label' => 'Status']) // Replace TextColumn with TemplateColumn for actions ->add('actions', TemplateColumn::class, [ 'label' => 'Actions', 'template' => 'users/_action_button.html.twig', // Path to your custom template ]) ->createAdapter(ORMAdapter::class, [ 'entity' => User::class ]) ->handleRequest($request); if ($table->isCallback()) { return $table->getResponse(); } return $this->render('users/index.html.twig', [ 'controller_name' => 'UsersController', 'datatable' => $table ]); }
Step 2: Create the Action Button Template
Make a new Twig template file at templates/users/_action_button.html.twig (match the path you specified in the controller). This template will render the button with a dynamic link to the user's page:
{# templates/users/_action_button.html.twig #} <a href="{{ path('user_show', {id: row.id}) }}" class="btn btn-sm btn-primary"> Voir l'utilisateur {# Or "View User" if you're using English #} </a>
Important Notes:
- Replace
user_showwith the actual name of your user detail route (check yourroutes.yamlor annotations to confirm this). - The
rowvariable in the template represents the currentUserentity from your DataTable, sorow.idwill automatically pull the user's ID. - You can style the button with Bootstrap classes (like
btn-primary) or custom CSS to match your app's design.
Step 3: Render the DataTable in Your Main Template
Make sure your users/index.html.twig includes the DataTable rendering code (you probably already have this, but just to confirm):
{# templates/users/index.html.twig #} {% extends 'base.html.twig' %} {% block body %} <h1>Utilisateurs</h1> {{ datatable_render(datatable) }} {% endblock %}
That's it! When you load the page, each row will have an "Actions" button that clicks through to the corresponding user's page, carrying their ID in the URL.
内容的提问来源于stack exchange,提问作者Kloni

