# Control Panel — Templates, Navigation, Settings CP templates, form macros, navigation, settings pages, permissions, and read-only mode. For controller patterns (CRUD, webhooks, API, routing), see `controllers.md`. For standalone components (widgets, utilities, slideouts, ajax), see `cp-components.md`. For visual patterns (tri-state controls, CSS variables, condition builders, asset bundles), see `cp-ui-patterns.md`. For building an element index (sources, columns, actions, sort options — `defineSources()`, `defineTableAttributes()`, `defineDefaultTableAttributes()`, `attributeHtml()`, `defineActions()`, `defineSortOptions()`), see `element-index.md`. ## Documentation - CP templates: https://craftcms.com/docs/5.x/extend/cp-templates.html - CP sections: https://craftcms.com/docs/5.x/extend/cp-section.html - CP edit pages: https://craftcms.com/docs/5.x/extend/cp-edit-pages.html - Permissions: https://craftcms.com/docs/5.x/extend/user-permissions.html - Utilities: https://craftcms.com/docs/5.x/extend/utilities.html - Widget types: https://craftcms.com/docs/5.x/extend/widget-types.html ## Common Pitfalls - Not wrapping settings UI in `allowAdminChanges` checks — settings should be read-only in production. - Hardcoding plugin name strings instead of using `Craft::t()` with the plugin handle translation category. - Missing `actionInput()` and `redirectInput()` in full-page forms — form submission won't route correctly. - Not passing `errors: entity.getErrors('field')` to form macros — validation errors won't display. - Registering CP nav items without checking user permissions first — users see nav items they can't access, leading to 403 errors. - Using raw HTML in CP templates instead of Craft's form macros — loses consistency, dark mode support, and accessibility features. - Not handling the `readonly` state for fields when `allowAdminChanges` is false — users can edit values they can't save. - Forgetting `csrfInput()` in custom forms that don't use `fullPageForm` — POST requests will be rejected. - Using `size` attribute with `type: 'number'` on `textField` — browsers ignore the HTML `size` attribute on ``. Craft's own Number field works around this by using `type: 'text'` with `inputmode: 'numeric'`. For number inputs, constrain width with `inputAttributes: { style: 'width: 6rem' }` or switch to a text input with `inputmode="numeric"` pattern. - Expensive `badgeCount` computation in `getCpNavItem()` — this method runs on **every CP page load** across the entire install, not just your plugin's pages. Badge counts must be extremely cheap: use a cached value (invalidated on relevant saves) or a simple indexed `COUNT(*)` query. Never run complex queries, N+1 patterns, or element queries with eager loading here. - Gating subnav entries on `allowAdminChanges` in `getCpNavItem()` — hides the settings link on production, making the page unreachable from the CP nav even though it should be viewable in read-only mode. Gate on permission (`can()`), not on admin changes. See Read-Only Mode section for the full three-node access path. - Leaving a plugin CP template without an underscore prefix when it isn't meant to be a direct route — Craft's CP template-routing fallback makes it reachable by URL, skipping your controller's `beforeAction()` gates entirely. See [CP template routing bypasses controllers](#cp-template-routing-bypasses-controllers). - Giving a plugin element one of Craft's reserved CP DOM IDs (`#notifications`, `#content`, `#tabs`, `#sidebar`, etc.) — Craft's CP JS caches chrome refs via `$('#foo')` during init and returns the first match in DOM order, so a plugin element with the same ID silently hijacks notification toasts, ARIA masking, or layout wiring. Pick feature-specific names (e.g. `notificationSettings`, not `notifications`) for tab keys, pane containers, slideout/HUD roots — anything you give an `id`. See [Reserved DOM IDs](#reserved-dom-ids) for the full list. ## Contents - [CP Templates](#cp-templates) — form macros, editable tables, tabbed settings, reserved DOM IDs, template routing fallback, VueAdminTable - [CP Navigation](#cp-navigation) - [Settings Pages](#settings-pages) — settings model, env var support, config-file override warnings (configWarning pattern), keeping settings inside the plugin's CP section, split settings pages (savePluginSettings footgun) - [Form Macros Reference](#form-macros-reference) — lightswitch vs checkbox, copytext, money, buttons + modifier classes, inner sidebar nav (`_includes/nav.twig`) - [Permissions](#permissions) - [Read-Only Mode (allowAdminChanges)](#read-only-mode-allowadminchanges) — controller setup, template patterns, disabled fields **Moved to separate files:** - Widgets, utilities, slideouts, ajax, alerts → `cp-components.md` - UI patterns, condition builders, asset bundles, markup patterns → `cp-ui-patterns.md` ## CP Templates ### Form Macros ```twig {% import '_includes/forms.twig' as forms %} {{ forms.textField({ label: 'Name'|t('my-plugin'), id: 'name', name: 'name', value: item.name, errors: item.getErrors('name'), required: true, first: true, }) }} {{ forms.lightswitchField({ label: 'Enable Sync'|t('my-plugin'), id: 'enableSync', name: 'enableSync', on: settings.enableSync, }) }} {{ forms.selectField({ label: 'Batch Size'|t('my-plugin'), id: 'batchSize', name: 'batchSize', value: item.batchSize, options: batchSizeOptions, }) }} ``` ### Editable Table Two variants: `editableTableField` (with label, instructions, error wrapper) and `editableTable` (raw table only, for embedding in custom layouts). #### Basic usage ```twig {{ forms.editableTableField({ label: 'Site Mappings'|t('my-plugin'), instructions: 'Map each site to a URI format.'|t('my-plugin'), id: 'sites', name: 'sites', cols: { siteId: { type: 'select', heading: 'Site'|t('my-plugin'), options: siteOptions }, uriFormat: { type: 'singleline', heading: 'URI Format'|t('my-plugin'), placeholder: 'items/{slug}' }, enabled: { type: 'lightswitch', heading: 'Enabled'|t('my-plugin') }, }, rows: siteRows, allowAdd: true, allowDelete: true, allowReorder: true, errors: settings.getErrors('sites'), }) }} ``` #### Column types | Type | Renders | Value in POST data | |------|---------|-------------------| | `singleline` | Text input | `string` | | `multiline` | Textarea (auto-grows) | `string` | | `number` | Number input | `string` (cast server-side) | | `checkbox` | Centered checkbox | `'1'` or absent | | `lightswitch` | Craft lightswitch toggle | `'1'` or `''` | | `select` | Dropdown (requires `options`) | Selected value `string` | | `date` | Date picker | `string` (Y-m-d format) | | `time` | Time picker | `string` (H:i format) | | `color` | Color picker | `string` (hex) | | `heading` | Non-editable display text | Not submitted | | `html` | Raw HTML (non-editable) | Not submitted | | `template` | Render a Twig template per cell | Depends on template | Column config keys: `type` (required), `heading`, `placeholder`, `class`, `width` (CSS width like `'30%'`), `thin` (boolean, minimal width), `options` (for `select`), `info` (tooltip text). #### Raw table (no field wrapper) ```twig {{ forms.editableTable({ id: 'mappings', name: 'mappings', cols: cols, rows: rows, allowAdd: true, allowDelete: true, allowReorder: true, defaultValues: { enabled: true, batchSize: '50' }, minRows: 1, maxRows: 10, staticRows: false, }) }} ``` Additional settings: `minRows`, `maxRows` (enforce row count limits), `defaultValues` (hash of column handle → default value for new rows), `staticRows` (when `true`, rows can't be added/deleted — useful for fixed configurations like site mappings where you show one row per site). #### Server-side handling POST data arrives as a nested array keyed by row ID: ```php // In controller action $rows = $this->request->getBodyParam('sites'); // $rows = [ // 'row1' => ['siteId' => '1', 'uriFormat' => 'items/{slug}', 'enabled' => '1'], // 'row2' => ['siteId' => '2', 'uriFormat' => 'articles/{slug}', 'enabled' => ''], // ] // Normalize — strip row IDs, cast types $normalized = []; foreach ($rows as $row) { $normalized[] = [ 'siteId' => (int)$row['siteId'], 'uriFormat' => $row['uriFormat'] ?? '', 'enabled' => (bool)($row['enabled'] ?? false), ]; } ``` Row IDs are auto-generated (e.g., `row1`, `new2`). Never rely on them — iterate the array values. New rows added by the user have IDs prefixed with `new`. When repopulating on validation failure, pass the raw `$rows` back as `rows` so the user's edits aren't lost. #### Populating rows from a model ```php // In controller, before rendering $siteRows = []; foreach ($settings->siteMappings as $mapping) { $siteRows[] = [ 'siteId' => $mapping['siteId'], 'uriFormat' => $mapping['uriFormat'], 'enabled' => $mapping['enabled'], ]; } // Pass to template return $this->renderTemplate('my-plugin/settings', [ 'siteRows' => $siteRows, 'siteOptions' => $this->_getSiteOptions(), ]); ``` #### JS interaction (Garnish) > For Garnish library primitives (`Garnish.Modal`/`HUD`/`DragSort`, `UiLayerManager`, focus/ARIA helpers, the `Garnish.Base.extend` class system), see the `craft-garnish` skill. This file covers Craft's higher-level `Craft.*` CP APIs built on top. The table auto-initializes as a `Craft.EditableTable` instance. Access it for programmatic manipulation: ```javascript // Get the instance (auto-attached to the container) var table = $('#sites').data('editable-table'); // Add a row programmatically table.addRow(false); // false = don't focus the new row // Listen for row changes $('#sites').on('addRow', function(ev) { // A row was added }); $('#sites').on('deleteRow', function(ev) { // A row was deleted }); ``` ### CP Layout ```twig {% extends '_layouts/cp.twig' %} {% set title = 'Settings'|t('my-plugin') %} {% set selectedSubnavItem = 'settings' %} {% set fullPageForm = true %} {% block content %} {{ actionInput('my-plugin/settings/save') }} {{ redirectInput('my-plugin/settings') }} {# Form fields here #} {% endblock %} ``` #### Layout regions for an edit screen `{% block content %}` fills only the main pane. A hand-built edit screen also wants a metadata sidebar and a collapsible details panel. `_layouts/cp.twig` reads each region as either a `{% block %}` or a same-named `{% set %}` var (verified against `vendor/craftcms/cms/src/templates/_layouts/cp.twig` — see the `{% set sidebar = (sidebar ?? block('sidebar') ?? '')|trim %}` lines). The var form wins when both are present, and is handier when the region is built with `{% set ... %}{% endset %}` capture: ```twig {% extends '_layouts/cp.twig' %} {% import '_includes/forms.twig' as forms %} {% set title = item.title %} {% set fullPageForm = true %} {# Right-hand collapsible details panel (metadata: status, dates, slug) #} {% block details %} {{ forms.lightswitchField({ label: 'Enabled'|t('my-plugin'), name: 'enabled', on: item.enabled, }) }} {{ forms.dateTimeField({ label: 'Post Date'|t('my-plugin'), name: 'postDate', value: item.postDate, }) }} {% endblock %} {# Left-hand page sidebar (e.g. a structure tree or filters) #} {% block sidebar %} {# nav, tree, or secondary controls #} {% endblock %} {% block content %} {{ actionInput('my-plugin/items/save') }} {{ redirectInput('my-plugin/items') }} {# main fields #} {% endblock %} ``` The layout exposes these regions (each available as a block or a `{% set %}` var of the same name): | Region | What it renders | |--------|-----------------| | `content` | The main content pane (always present). | | `sidebar` | Left-hand page sidebar. Adds the `has-sidebar` class to `#main-content`. | | `details` | Right-hand collapsible details panel — metadata, status, dates. Adds `has-details`. | | `footer` | A footer strip inside the content pane (below `content`). | | `contextMenu` | Markup beside the breadcrumbs in the global header. | | `toolbar` | Toolbar row beside the page title. | Setting `details` (block or var) is what makes the right-hand panel and its disclosure toggle appear — there's no separate flag. The same goes for `sidebar` and `footer`: the region only renders if its block/var is non-empty. ### Tabbed Settings Pages Two approaches for multi-tab CP pages: Twig-level tabs (template-driven) and PHP-level tabs (controller-driven via `asCpScreen()`). #### Tabs switch panes — they never navigate `Craft.Tabs` intercepts every tab click: the compiled handler (`web/assets/cp/dist/cp.js`) calls `preventDefault()` and `selectTab()` unconditionally (the only carve-out is ctrl/cmd-click on a `#` href), and `selectTab()` only moves `.sel`/ARIA state while `Craft.CP`'s `selectTab` listener toggles `hidden` on the pane matching `$(tab.href)`. A tab whose `url` is a real page URL therefore does nothing when clicked — no navigation, and no pane to match. No core template sets URL-based tabs (grepping `set tabs` under `src/templates/` hits only the layout internals and the Matrix block partial). The decision rule: `tabs` is for same-page anchor panes only. When permission-gated or structurally separate sections live at their own URLs, use the inner sidebar nav idiom instead — `settings/users/_layout.twig` renders `_includes/nav` in `{% block sidebar %}` with one URL per section (see [Inner sidebar navigation](#inner-sidebar-navigation-_includesnavtwig)). #### Twig-level tabs Set the `tabs` variable in your template; the CP layout renders the tab bar automatically when `tabs` has more than one entry. Each tab is an **anchor to a same-page pane** (`url: '#paneId'`) — see [Anchor-based tabs](#anchor-based-tabs-single-page) below for the full example, and use `selectedTab` to highlight the active pane. Don't give a tab a real page `url` or register CP URL rules per tab — those tabs are dead clicks (see [Tabs switch panes](#tabs-switch-panes--they-never-navigate) above). When sections are structurally separate or permission-gated and genuinely need their own URLs, use the inner sidebar nav idiom instead — `settings/users/_layout.twig` renders `_includes/nav` in `{% block sidebar %}` with one URL per section. **Don't hand-write or include the tab strip.** `_includes/tabs.twig` is a private helper that `_layouts/cp.twig` calls internally to render the strip from the `tabs` variable in *its own* rendering context. Including the partial yourself — or emitting the markup by hand — produces the tab strip but no JS wiring, no ARIA controller setup, no error highlighting per tab. The strip's real container is `