Skip to content

Dashboard Extensions

Andreas Michael edited this page Dec 2, 2026 · 1 revision

Dashboard Extensions

The Member Self-Service Dashboard (/memberships/dashboard) is built around a pluggable Drupal Plugin system (Plugin\DashboardSection). Both EMM's built-in sections (Application, Digital Wallets, Guest Passes) and companion modules (such as Estia Housing) register sections using the PHP #[DashboardSection] attribute with no manual services.yml wiring required.

How It Works

MembershipDashboard delegates section discovery and lifecycle to plugin.manager.membership_dashboard_section (Drupal\esn_membership_manager\Dashboard\DashboardSectionManager):

  1. Discovery: Scans src/Plugin/DashboardSection/ across all enabled modules for classes annotated with #[DashboardSection].
  2. Filtering & Ordering: Calls isApplicable($application) on each section and sorts active sections by weight ascending (tie-broken alphabetically by plugin ID).
  3. Sidebar Navigation: Builds the collapsible Material Symbols sidebar from Overview (#overview) plus each active section's getNavItem($application).
  4. Overview Quick Action: Collects getQuickActions($application) from all active sections and renders the single action with the highest priority.
  5. Fault Isolation: Each section's build() call is wrapped in a try/catch, so an exception in a companion module is logged without breaking the rest of the dashboard.

Creating a Dashboard Section Plugin

Place a class under src/Plugin/DashboardSection/ in your module, annotate it with #[DashboardSection], and extend DashboardSectionPluginBase.

DashboardSectionPluginBase already implements ContainerFactoryPluginInterface with a default create() factory — only override create() when your section injects services.

<?php

declare(strict_types=1);

namespace Drupal\my_module\Plugin\DashboardSection;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\esn_membership_manager\Attribute\DashboardSection;
use Drupal\esn_membership_manager\Dashboard\DashboardSectionPluginBase;
use Drupal\esn_membership_manager\Dashboard\UI\BadgeVariant;
use Drupal\esn_membership_manager\Dashboard\UI\DashboardBadge;
use Drupal\esn_membership_manager\Dashboard\UI\DashboardPanel;
use Drupal\esn_membership_manager\Dashboard\UI\DashboardQuickAction;
use Drupal\esn_membership_manager\Dashboard\UI\DashboardSectionBuilder;
use Drupal\esn_membership_manager\Entity\Application\ApplicationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

#[DashboardSection(
    id: 'my_section',
    label: new TranslatableMarkup('My Section'),
    icon: 'home',
    weight: 40,
)]
class MyDashboardSection extends DashboardSectionPluginBase
{
    public function __construct(
        array $configuration,
        $plugin_id,
        $plugin_definition,
        protected EntityTypeManagerInterface $entityTypeManager,
    ) {
        parent::__construct($configuration, $plugin_id, $plugin_definition);
    }

    public static function create(
        ContainerInterface $container,
        array $configuration,
        $plugin_id,
        $plugin_definition,
    ): static {
        return new static(
            $configuration,
            $plugin_id,
            $plugin_definition,
            $container->get('entity_type.manager'),
        );
    }

    public function isApplicable(ApplicationInterface $application): bool
    {
        return $application->isApproved();
    }

    public function getQuickActions(ApplicationInterface $application): array
    {
        return [
            new DashboardQuickAction(
                label: $this->t('Explore'),
                href: Url::fromRoute('my_module.listing'),
                priority: 10,
                icon: 'home',
            ),
        ];
    }

    public function build(ApplicationInterface $application, FormStateInterface $form_state): DashboardSectionBuilder
    {
        $panel = (new DashboardPanel($this->t('Your Items')))
            ->headerLink($this->t('Browse All'), Url::fromRoute('my_module.listing'))
            ->table(
                headers: [
                    'name' => $this->t('Item'),
                    'status' => $this->t('Status'),
                ],
                rows: [
                    [
                        'name' => 'Example Item',
                        'status' => new DashboardBadge($this->t('Approved'), BadgeVariant::Success),
                    ],
                ],
                emptyMessage: $this->t('You have no items yet.'),
            );

        return $this->createSection($this->t('My Section Heading'))
            ->description($this->t('Track your items here.'))
            ->addPanel($panel, 'items');
    }
}

Clear Drupal's caches (drush cr) after adding a new plugin so DashboardSectionManager discovers it.

Soft-Dependency Safety: Because Drupal's AttributeClassDiscovery automatically records module provider dependencies and skips plugins whose parent classes are unavailable, placing plugins in src/Plugin/DashboardSection/ is safe even for modules where esn_membership_manager is optional.


Attribute Reference (#[DashboardSection])

Namespace: Drupal\esn_membership_manager\Attribute\DashboardSection

Parameter Type Default Description
id string (required) Unique machine ID and HTML anchor (#<id>).
label ?TranslatableMarkup null Label shown in the collapsible sidebar navbar.
icon ?string null Material Symbols Outlined ligature name (e.g. home, wallet).
weight int 50 Ordering weight; lower values appear higher in the page and navbar.
deriver ?class-string null Optional Drupal plugin deriver class.

Built-In Section Weights & Quick Action Priorities

Plugin ID Class Weight Icon Quick Actions (Priority)
application ApplicationSection 10 assignment_ind Pay for ESNcard (80), Get an ESN card (60)
wallet WalletSection 20 wallet Add to Wallet (100)
guest GuestPassSection 30 group_add (none)

Companion modules should generally use weights >= 40 and low Quick Action priorities (e.g., 10–30) so EMM's core membership actions (Wallet, ESNcard payment) take precedence when applicable.

Dynamic Navigation Items

By default, DashboardSectionPluginBase::getNavItem() builds a DashboardNavItem from the attribute's label and icon (or returns null if either is omitted). Override getNavItem() to add dynamic indicators:

public function getNavItem(ApplicationInterface $application): ?DashboardNavItem
{
    $base = parent::getNavItem($application);
    return $base === null ? null : new DashboardNavItem(
        label: $base->label,
        icon: $base->icon,
        badgeCount: 3,      // Optional pill count badge
        hasAlert: false,    // Optional red attention dot (takes precedence over badgeCount)
    );
}

Dashboard UI Builders

All visual components live under Drupal\esn_membership_manager\Dashboard\UI\ and implement DashboardRenderableInterface (toRenderArray(): array), so they can be nested directly inside panels and table cells.

DashboardSectionBuilder

Construct directly via new DashboardSectionBuilder($id, $title) or the $this->createSection($title) helper on DashboardSectionPluginBase:

  • description(string|MarkupInterface ...$paragraphs) — Renders .section-description paragraphs beneath the <h2>.
  • addPanel(DashboardPanel $panel, ?string $key = null) — Appends a styled .panel card.
  • addHiddenAction(string $key, string $sectionID, string $action, string $domID, ...) — Adds a hidden submit button bound to MembershipDashboard::handleSectionSubmit() (for inline edit toggles or auto-submit file uploads).
  • addElement(string $key, array|DashboardRenderableInterface $element) — Escape hatch for arbitrary render/form elements.
  • attachLibrary(string $library) — Attaches a Drupal asset library to the section.
  • addClass(string $class) / weight(int $weight) — Adds custom CSS classes or overrides render weight.

DashboardPanel

Construct via new DashboardPanel($title):

  • Header controls:
    • headerLink($label, Url|string $url, ?string $icon = null, bool $external = false) — Renders a .panel-header-link navigation link (never intercepted by inline-edit JS).
    • headerEditToggle(string $submitElementID, $label = 'Edit') — Renders an inline Edit/Save toggle targeting a hidden submit button's DOM ID.
  • Body builders:
    • table(array $headers, array $rows, $emptyMessage = null, string $key = 'table') — Renders a .panel-table and automatically normalizes DashboardRenderableInterface and render-array cells into ['data' => ...]. When $rows is empty and $emptyMessage is provided, renders an empty state automatically.
    • emptyState($message, ?string $icon = null, string $key = 'empty') — Renders a .panel-body.panel-empty block.
    • body($content, string $key = 'body') — Wraps plain text, a render array, or a DashboardRenderableInterface in .panel-body.
    • infoGrid(array $fields, string $key = 'grid') + DashboardPanel::infoField($label, array $element, bool $readonly = false, bool $panelInput = false) — Builds a responsive .panel-body.info-grid with .info-item field wrappers.
    • dividedBody(array $columns, string $key = 'divided_body') — Renders side-by-side columns separated by .panel-divider (skipping empty columns).
    documentRow($title, $subtitle, string $icon, $trailing, bool $isError = false, bool $borderTop = true, string $trailingKey = 'trailing', string $key = 'document') — Builds a .document-list / .document-item row with a trailing badge or file upload element. * addSubmitButton($label, string $sectionID, string $action, ButtonVariant $variant = ButtonVariant::Primary, bool $validate = false, array $limitValidationErrors = [], string $key = 'submit') — Adds a form submit button wired to MembershipDashboard's central action dispatcher.
    • addElement(string $key, array|DashboardRenderableInterface $element) — Adds an arbitrary Form API / render element.

DashboardBadge & BadgeVariant

new DashboardBadge($this->t('Approved'), BadgeVariant::Success);
new DashboardBadge($this->t('Pending'), BadgeVariant::Warning, 'schedule');
new DashboardBadge($this->t('Declined'), BadgeVariant::Error);
new DashboardBadge($this->t('Info'), BadgeVariant::Info);

Default Material icons per BadgeVariant: Success → check_circle, Warning → warning_amber, Error → cancel, Info → info. Pass '' for $icon to omit the icon.


Interactive Sections (Form Validation & Submission)

Sections that include interactive form buttons implement Drupal\esn_membership_manager\Dashboard\InteractiveDashboardSectionInterface:

use Drupal\Core\Form\FormStateInterface;
use Drupal\esn_membership_manager\Dashboard\InteractiveDashboardSectionInterface;
use Drupal\esn_membership_manager\Entity\Application\ApplicationInterface;

class MyInteractiveSection extends DashboardSectionPluginBase implements InteractiveDashboardSectionInterface
{
    public const string ACTION_CANCEL = 'cancel_item';

    public function validateAction(string $action, array &$form, FormStateInterface $form_state, ApplicationInterface $application): void
    {
        if ($action === self::ACTION_CANCEL && empty($form_state->getValue('item_id'))) {
            $form_state->setErrorByName('item_id', $this->t('Please select an item.'));
        }
    }

    public function submitAction(string $action, array &$form, FormStateInterface $form_state, ApplicationInterface $application): void
    {
        if ($action === self::ACTION_CANCEL) {
            // Perform mutation using the already-authenticated $application.
        }
    }
}

When a button created with DashboardPanel::addSubmitButton() or DashboardSectionBuilder::addHiddenAction() is triggered:

  1. MembershipDashboard::handleSectionValidate() / ::handleSectionSubmit() reads #dashboard_section and #dashboard_action from the triggering element.
  2. EMM verifies the active session, loads $application, and confirms $section->isApplicable($application).
  3. EMM dispatches to validateAction() / submitAction().

Because only string callbacks ('::handleSectionSubmit') are placed in $form, plugin services are never serialized into Drupal's form cache or AJAX state.


Altering Section Definitions

Any module can adjust discovered section definitions (such as reordering weights, changing icons/labels, or removing a section) by implementing hook_membership_dashboard_section_info_alter():

/**
 * Implements hook_membership_dashboard_section_info_alter().
 */
function my_module_membership_dashboard_section_info_alter(array &$definitions): void
{
    if (isset($definitions['estia'])) {
        $definitions['estia']['weight'] = 25;
    }
}

Clone this wiki locally