Saltar al contenido
MovieMaster

Desarrolladores: plugins y themes

Admin pages for plugins

3 min de lectura 9 apartados

En esta página

How to give a plugin its own section in the admin panel: the page, its menu entry, the controller, views that match the panel's look, permissions, and admin hooks. Simple settings don't need any of this: with $plugin->setting() the core renders the form for you.

Registering a page #

php
// plugin.php
$plugin->adminPage('panel', __('my-plugin::menu'), [MyPlugin\AdminController::class, 'handle'], [
    'parent' => 'top',
    'icon'   => 'star',
    'cap'    => 'manage_content',
    'order'  => 60,
]);
ArgumentWhat it is
$keyThe page's identifier within the plugin. Forms the URL: /admin/p/<slug>/<key>.
$labelMenu text and the page's default title. Pass it already translated.
$handler[Class::class, 'method'], a closure, or any callable. Called just like a route controller.
$optionsOptions from the table below.
OptionDefaultEffect
parentsystemThe menu group it appears in: movies, series, content, import, player, appearance, system, or top for its own top-level entry.
icondotMenu icon (list below). Submenus usually leave it at dot.
capmanage_settingsCapability required to see the entry and open the page.
order50Position within the group (lower = higher up). The core's top-level entries range from 0 to 97.
methods['GET', 'POST']HTTP methods the URL accepts.

Each page gets the route name admin.plugin.<slug>.<key>, so its URL is obtained with route('admin.plugin.my-plugin.panel'). You can register several pages with different keys; each one is a menu entry.

home, video, film, tv, folder, tag, star, image, file, palette, layout, plug, users, user, settings, refresh, cpu, server, dot, sliders, search, list, clock, inbox, globe, layers, play, filter, key, download, upload, check, alert, info, trash, edit, eye, plus, external.

The same names work inside views too: @include('admin::partials/icon', ['name' => 'refresh']).

The controller #

Extends MovieMaster\Admin\AdminController. It gives you the panel layout, notices, and redirects with a message:

MethodWhat it does
render(string $template, array $data = [], ?Request $request = null): ResponseRenders the view with the layout's variables (user, menu, notices, errors). Pass page_title in $data for the title and breadcrumb. The response is sent with no-store.
redirect(string $to, ?string $success = null, ?string $error = null): ResponseRedirects and leaves a green ($success) or red ($error) notice on the next page.
back(Request $request, array $errors, ?string $to = null): ResponseGoes back to the form with the field errors and what had been typed.
json(mixed $data, int $status = 200): ResponseJSON response, for calls from JavaScript.

Available properties: $this->view, $this->session, $this->auth, and $this->menu. If you need more services, add them to the constructor and call the parent's:

php
<?php
declare(strict_types=1);

namespace MyPlugin;

use MovieMaster\Admin\AdminController as Base;
use MovieMaster\Admin\Menu;
use MovieMaster\Auth\Auth;
use MovieMaster\Auth\Session;
use MovieMaster\Http\Request;
use MovieMaster\Http\Response;
use MovieMaster\View\Engine;

final class AdminController extends Base
{
    public function __construct(Engine $view, Session $session, Auth $auth, Menu $menu, private Repository $repo)
    {
        parent::__construct($view, $session, $auth, $menu);
    }

    public function handle(Request $request): Response
    {
        $here = route('admin.plugin.my-plugin.panel');

        if ($request->isPost()) {
            $name = trim($request->string('name'));
            if ($name === '') {
                return $this->back($request, ['name' => __('my-plugin::name_required')]);
            }
            $this->repo->create($name);
            return $this->redirect($here, __('my-plugin::saved'));
        }

        return $this->render('my-plugin::admin', [
            'page_title' => __('my-plugin::menu'),
            'items' => $this->repo->all(),
            'here' => $here,
        ], $request);
    }
}

A single URL handles both GET (render) and POST (save). If the page has several actions, tell them apart with a hidden field (<input type="hidden" name="action" value="delete">) and a switch. For several views on the same page, use a ?tab= parameter.

Views with the panel's look #

Plugin views extend the panel layout with @extends('admin::layout'):

html
{{-- views/admin.tpl --}}
@extends('admin::layout')

@section('actions')
  <a class="btn" href="{{ route('admin.settings', ['group' => 'plugin-my-plugin']) }}">
    @include('admin::partials/icon', ['name' => 'settings']) {{ __('admin.menu.settings') }}
  </a>
@endsection

@section('help')
  <p>{{ __('my-plugin::help') }}</p>
@endsection

@section('content')
<div class="grid two">
  <section class="card">
    <div class="card-head"><h2>{{ __('my-plugin::new') }}</h2></div>
    <form method="post" action="{{ $here }}">
      @csrf
      <div class="field {{ isset($errors['name']) ? 'has-error' : '' }}">
        <label for="name">{{ __('my-plugin::name') }}</label>
        <input id="name" name="name" value="{{ old('name') }}" required>
        @if(isset($errors['name']))<p class="error">{{ $errors['name'] }}</p>@endif
      </div>
      <div class="form-actions">
        <button class="btn primary" type="submit">{{ __('common.save') }}</button>
      </div>
    </form>
  </section>

  <section class="card">
    <div class="card-head"><h2>{{ __('my-plugin::list') }}</h2></div>
    @if($items)
    <div class="table-wrap">
      <table class="table">
        <thead><tr><th>{{ __('my-plugin::name') }}</th><th></th></tr></thead>
        <tbody>
        @foreach($items as $it)
          <tr>
            <td>{{ $it['name'] }}</td>
            <td>
              <form method="post" action="{{ $here }}" class="inline" data-confirm="{{ __('my-plugin::confirm_delete') }}">
                @csrf
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="{{ $it['id'] }}">
                <button class="btn ghost small">@include('admin::partials/icon', ['name' => 'trash'])</button>
              </form>
            </td>
          </tr>
        @endforeach
        </tbody>
      </table>
    </div>
    @else
      <p class="empty muted">{{ __('my-plugin::empty') }}</p>
    @endif
  </section>
</div>
@endsection

Layout sections #

SectionWhere it goes
contentThe page's body. Required.
actionsButtons to the right of the title (.page-actions).
helpA "?" button next to the title that expands this content.
page_headReplaces the whole header (title, actions, and help). For custom headers.
headInside the panel's <head>, only on this page: your own <style> or <script>.

The layout already shows the title (page_title), the breadcrumb, and redirect()'s notices.

Layout variables #

Besides what you pass in $data, the view receives: $user (the panel's logged-in user), $menu, $flash (success/error), $errors (from back(), per field), and $page_title. To repopulate a form after an error, use old('field', $defaultValue).

Classes and components #

The panel's CSS is already loaded. Use its classes so your page looks like the rest:

ClassUse
.card, .card-head, .cardsCards with a header.
.grid.twoTwo columns that collapse to one on mobile.
.field, .check, .rowA form field with its label; a checkbox; several fields on one row. A field with an error gets .field.has-error and the message in <p class="error">.
.form-actions (.sticky)The form's button bar (sticks to the bottom with .sticky).
.btn, .btn.primary, .btn.ghost, .smallButtons.
.table-wrap + .table (.compact)Tables with horizontal scroll on mobile.
.badge, .tagSmall status labels.
.muted, .small, .empty, .inlineSecondary text, small text, empty state, inline form.
.kpi, .kpi-head, .kpi-valueHighlighted figures.

For your own styles, use the panel's variables so you respect both light and dark mode: --color-bg, --color-card, --color-card-2, --color-ink, --color-ink-2, --color-muted, --color-line, --color-line-2, --color-primary, --color-primary-soft, --color-on-primary, --color-ok, --color-ok-soft, --color-warn, --color-warn-soft, --color-bad, --color-bad-soft, --color-info, --color-info-soft, --radius-sm, --radius-md, --radius-lg. Prefix your classes (.mp-…) to avoid clashing with the panel's.

Behaviors via attributes #

admin.js adds behavior to any markup that carries these attributes, including on a plugin's pages:

AttributeEffect
data-confirm="Are you sure?"On a <form>, button, or link: asks for confirmation in a dialog before proceeding.
[data-tabs] with buttons [data-tab="x"] and panels [data-panel="x"]Tabs within the page.
.field[data-hide-when="name"]Hides the field while the name checkbox is checked.
input[data-slug-from="#title"]Fills in a slug based on another field.
[data-media-picker] with a hidden input, [data-pick], and [data-clear]Media library picker.
label[data-dropzone] with input[type=file]Drag-and-drop file zone.

Forms and security #

  • CSRF: every request to /admin that isn't GET, HEAD, or OPTIONS must carry the token. Add @csrf to every form; in JavaScript, send the X-CSRF-Token header. The panel layout already prints the token in <meta name="csrf-token">. Without a token, the response is a 419 error.
  • Permissions: the core checks the page's cap before calling your controller. If there are more sensitive actions inside, check them yourself: if (!$this->auth->can('manage_settings')) { … }.
  • Escape anything coming from the database with {{ }}. Use {!! !!} only with HTML you generated yourself.
  • Secrets: store API keys with a secret-type setting (encrypted in the database), never in a plain text field.
js
// Call from JavaScript to your own panel page
await fetch(url, {
    method: 'POST',
    headers: { 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.content ?? '' },
    body: new FormData(form),
});

Capabilities and roles #

CapabilityWho has it
access_adminEvery panel user.
manage_content, upload_mediaadmin, editor, and author.
manage_terms, manage_people, manage_pages, publish_content…admin and editor.
manage_settings, manage_usersadmin only.

A new capability (my_plugin_moderate) is only granted to admin until you give it to another role with the role_capabilities filter. The full table is in the PHP API.

Your own routes in the panel #

If you need URLs that aren't a menu entry (a JSON endpoint, an export, a button's action), register them with the admin_routes action. They live under /admin, with the panel's session, login check, and CSRF:

php
add_action('admin_routes', function (\MovieMaster\Http\Router $r): void {
    $r->get('/my-plugin/export.csv', [MyPlugin\Export::class, 'csv'], [
        'name' => 'my-plugin.export',   // route('admin.my-plugin.export')
        'cap'  => 'manage_content',
    ]);
    $r->post('/my-plugin/api/sort', [MyPlugin\Api::class, 'sort'], ['cap' => 'manage_content']);
});

The name gets the admin. prefix. Without cap, access_admin is enough. Always use a prefix with your plugin's slug so you don't clash with core routes.

Modifying the menu #

The admin_menu filter receives every entry before permission filtering. Each entry is an array with key, label, route (route name or URL), icon, cap, order, and children (the group's entries, by key):

php
add_filter('admin_menu', function (array $items): array {
    // An external link inside the System group
    $items['system']['children']['my-plugin-docs'] = [
        'key' => 'my-plugin-docs', 'label' => 'My Plugin help',
        'route' => 'https://my-plugin.com/docs', 'icon' => 'dot',
        'cap' => 'manage_settings', 'order' => 99, 'match' => null, 'children' => [],
    ];
    // Hide an entry from anyone who isn't an admin
    if (isset($items['import']['children']['queue'])) {
        $items['import']['children']['queue']['cap'] = 'manage_settings';
    }
    return $items;
});

The core's group keys are dashboard, movies, series, content, import, player, seo, appearance, settings, and system. For a page from your own plugin, you don't need this filter: adminPage() already creates the entry.

Plugin settings #

Fields declared with $plugin->setting() appear under Settings, in the plugin's group. Link to them from your page:

php
route('admin.settings', ['group' => 'plugin-my-plugin'])

And read them with $plugin->get('key') or, from a class, with setting('plugin.my-plugin.key'). Field types, validation, and hide_when are covered in Creating plugins.

Panel hooks #

HookTypeWhat for
admin_menufilterChange menu entries.
admin_routesactionRegister routes under /admin.
admin_headactionPrint in the <head> of every panel page (your plugin's CSS).
admin_footeractionPrint before </body> of the panel (JavaScript).
admin_dashboard_widgetsfilterAdd cards to the dashboard.
admin_dashboard_status_cardsfilterAdd cards to the dashboard's status block.
admin_search_resultsfilterAdd results to the panel's search.
admin_settings_fieldactionYour own HTML below a Settings field.
admin_settings_links_forfilterLinks next to a Settings field.
admin_titles_index_top, admin_title_form_top, admin_title_actionsactionSlots in the titles listing and editor.
admin_catalog_panelactionUnder the Admin → Catalog form.
admin_onboarding_steps, admin_onboarding_itemsfilterSteps of "Getting started".

Arguments and details for each are in the hooks reference.

A dashboard widget #

php
add_filter('admin_dashboard_widgets', function (array $widgets): array {
    if (!app(\MovieMaster\Auth\Auth::class)->can('manage_content')) {
        return $widgets;
    }
    $n = (int) db()->table('my_plugin_items')->count();
    $widgets[] = [
        'title' => __('my-plugin::widget'),
        'html'  => '<p class="kpi-value">' . e((string) $n) . '</p>'
                 . '<a class="btn small" href="' . e(route('admin.plugin.my-plugin.panel')) . '">' . e(__('my-plugin::open')) . '</a>',
    ];
    return $widgets;
});

The html is printed as-is inside a .card: escape your data yourself with e(). The cards show to every panel user, so check the capability before adding yours.

CSS and JavaScript across the whole panel #

php
add_action('admin_head', function () use ($plugin): void {
    echo '<link rel="stylesheet" href="' . e($plugin->asset('admin.css')) . '">';
});
add_action('admin_footer', function () use ($plugin): void {
    echo '<script src="' . e($plugin->asset('admin.js')) . '" defer></script>';
});

If only your page needs it, put it in your view's @section('head') instead of loading it across the whole panel.

Best practices #

  • One menu entry per plugin is almost always enough. Organize the rest with tabs (?tab=).
  • Pick the minimum cap that makes sense: manage_content for content tools, manage_settings for configuration.
  • Translate every label (__('my-plugin::…')) and test the page in both Spanish and English.
  • Test on mobile: the panel is responsive and your tables should sit inside .table-wrap.
  • Long-running tasks (imports, scanning the catalog) don't belong in the request: put them in the job queue and show progress.
  • If your page changes public content, purge the affected page cache. See page cache.

¿Te quedó alguna duda?

Escríbenos y te ayudamos con tu caso.

Hablar con nosotros
¿Hablamos?