# Card API Developer Guide Use Cacti's Card API when a plugin needs a dashboard of movable panels, or when an existing page needs a small chart. PHP renders the measurements as HTML or SVG. The shared stylesheet lays out the cards. The JavaScript controller handles keyboard and pointer interaction and calls your plugin when it needs new content or a layout saved. The example below builds two cards from sample poller measurements. You can move a card, expand its details, and refresh it from PHP. It runs on the Cacti `develop` and `1.2.x` revisions listed under [Implementation references](#implementation-references). The 1.2.x example was tested on a 1.2.32 maintenance checkout. Check which card helpers your installed build provides before using the example. ![Poller load and device availability][overview] ## Choose the parts you need | Use case | What to load or supply | | --- | --- | | Show a gauge, bar, or statistic in an existing Cacti page | Call a PHP widget helper and print its return value. | | Lay out several cards | Render a `.ccGrid` with one direct `.ccCard` child per card. | | Enable card controls | Call `CactiCards.init(grid, adapter)` after inserting the grid. | | Save a layout or load fresh data | Implement the corresponding adapter callbacks in the plugin. | Cacti's standard page header includes `include/css/cards.css`, `include/css/card-widgets.css`, and `include/js/cards.js` on both tested branches. The PHP helpers live in `lib/html.php`. On older installations, check for the helpers and the controller before advertising these controls. A plugin that emits a standalone fragment relies on the enclosing page to load the assets. ## Build the example plugin [Download the example plugin](resources/carddemo.zip) and extract it into your development installation’s `plugins/` directory, or create `plugins/carddemo/` and copy the four standalone dashboard files below. The sample uses fixed measurements so you can compare your result with the screenshots without configuring a poller. ### INFO ```ini [info] name = carddemo version = 1.0 longname = Card API Example author = Example Maintainer homepage = https://www.cacti.net compat = 1.2.32 ``` ### setup.php Register the page as a realm so the full dashboard and the refresh response use the same Cacti permission check. ```php __('Poller load', 'carddemo'), 'devices' => __('Device availability', 'carddemo'), ]; function carddemo_render($id, $title, $expanded) { $load = $id === 'load'; ?>

96, 'severity' => 'up', 'label' => __('48 up', 'carddemo')], ['percent' => 4, 'severity' => 'down', 'label' => __('2 down', 'carddemo')], ], true); } ?>
$title) { carddemo_render($id, $title, false); } ?>

Intropage > Panel Library**, look for the source **Carddemo**. Open the Intropage dashboard as a user with access to the panel. In the **Panels ...** menu select **Carddemo - Worker capacity**. The gauge displays **72%**. The panel can also update on the next Intropage polling cycle. ![Worker capacity gauge rendered within the Intropage dashboard][ip-shot] ### Register your provider The CLI checks that both plugins are enabled, loads Intropage's `includes/functions.php`, and checks for `intropage_register_panel`. Keep this check in optional integrations so older or absent hosts do not prevent your plugin from loading. The registration in the archive uses: ```php $result = intropage_register_panel([ 'panel_id' => 'carddemo_capacity', 'plugin' => 'carddemo', 'name' => __('Worker capacity', 'carddemo'), 'description' => __('Example worker pool utilization', 'carddemo'), 'class' => 'carddemo', 'level' => PANEL_SYSTEM, 'refresh' => 300, 'include_file' => 'plugins/carddemo/intropage-panel.php', 'update_func' => 'carddemo_update_capacity', ]); ``` Use a stable, plugin-prefixed ID, the installed plugin's directory name, and a readable PHP callback file under `plugins/`. A successful call returns `true`. Validation failure returns an array of messages, so compare the result strictly with `true`. The host persists the definition. Register on installation or an explicit integration upgrade. Registering the same ID again replaces its definition, including fields you omitted. Use `intropage_update_panel_registration()` to change selected fields. ### Render, authorize, and remove a panel Intropage loads the provider file when it builds the panel library. The callback calls the same core widget helper as a standalone page and saves the result for the supplied user: ```php function carddemo_update_capacity($panel, $user_id) { $panel['alarm'] = 'yellow'; $panel['data'] = card_gauge(72, '72%', __('Worker utilization', 'carddemo'), 'warn'); save_panel_result($panel, $user_id); } ``` The example uses `PANEL_SYSTEM` because its sample is identical for everyone. Use `PANEL_USER` for user-specific data, restrict the query to objects the supplied user can view, and save the result with that user ID. The **Intropage Panel Library** realm controls administration. Grant panel visibility separately to the intended dashboard users or groups. If you add a details callback, declare its request variables, read them with `intropage_validate_request_vars()`, and check access to the selected item. A disabled registration keeps its definition but loses its current placements. Re-enabling makes it available to add again. The example's uninstall callback calls `intropage_unregister_plugin_panels('carddemo')` when the API is available. Unregistering also removes the provider's data, placements, and panel permissions. See the [Intropage registration API][ip-api] for individual enable, disable, update, and removal calls. ## Integrate with other Cacti plugins On the reviewed plugin default branches, Intropage exposes the external registration API above. Several other dashboards use the shared card markup or controller with a catalog owned by the host plugin. For a contribution to one of those dashboards, add the card to its catalog, implement its renderer, and test its own refresh and permission paths. Register separately with Intropage if users should see it there too. | Plugin dashboard | Where to integrate a card | | --- | --- | | APC UPS | Choose the per-UPS or fleet catalog. Register the key in that catalog and render the body for the selected UPS or fleet. [APC UPS dashboard][apc-host] | | Host MIB | Add metadata and a body renderer to the host dashboard. Check availability for the selected device and preserve its host scope on refresh. [Host MIB dashboard][hmib-host] | | MacTrack | Add the key and title to the dashboard catalog and implement the matching card body. Its JavaScript adapter reloads cards by key. [MacTrack dashboard][mac-host] | | Syslog | Extend the status dashboard's card definitions and renderer. Preserve its filters when fetching refreshed markup. [Syslog dashboard][sys-host] | | TopX | Extend the overview catalog and select the records for the requested timespan. Its adapter can refresh the body in place. [TopX dashboard][topx-host] | | Alarm Manager | Its alarm statistics page renders shared card headers and bodies with a plugin-specific collapse button and chart loader. Extend that page's chart list and data response. [Alarm Manager dashboard][alarm-host] | ### Use existing plugin data in Intropage Intropage also ships panels for other plugins. These definitions live in Intropage. Enable the data-providing plugin, grant the relevant panel permission, and use the dashboard picker. Reuse the existing panel when it already shows what you need. | Data provider | What Intropage already displays | | --- | --- | | MacTrack | Device-tracking details and sites. [MacTrack panels][ip-mac] | | Syslog | Details, top devices and message levels. [Syslog panels][ip-sys] | | Thold | Threshold status and recent threshold events. [Threshold panels][ip-thold] | | Maint | Maintenance schedule details. [Maintenance panel][ip-misc] | | Webseer | Webseer checks for installations using this plugin. [Webseer panel][ip-misc] | | Servcheck | Service-check details. [Servcheck panel][ip-misc] | | Monitor | The Analyze panel can report devices missing monitoring when Monitor is enabled. This is part of the existing analysis panel. [Analyze panel][ip-monitor] | ## Choose a widget All five helpers return a string. Pass plain text labels, including translated labels, and print the returned HTML once. The helpers escape their labels. Give each measurement a unit or a denominator that the reader can interpret. | Helper and arguments, in order | What the reader sees | | --- | --- | | `card_gauge($percent, $center_label, $sub_label = '', $severity = 'none')` | A semicircle filled from 0 to 100 with a central value and optional caption. | | `card_bar($percent, $label = '', $severity = 'none')` | A horizontal percentage bar and optional label beneath it. | | `card_stat($value, $label)` | A large formatted value with a caption. Format its units before passing it. | | `card_stackbar($segments, $legend = false)` | One bar with a segment for each array entry. Each entry has `percent`, `severity`, and an optional `label`. Set the second argument to true to show labeled legend chips. | | `card_bullet($min, $avg, $max, $label, $summary = '', $severity = 'none', $scale_min = 0.0, $scale_max = 100.0)` | A colored band from minimum to maximum, an average marker, and the two scale endpoints. All five numbers use the same measurement unit. | Calculate percentages from a common total before building a stacked bar. The helper clamps individual percentages to the range 0–100 and leaves their relative totals to the caller. For a bullet, supply an increasing scale and measurements from the same sampling window. Handle missing measurements and a zero denominator before calling a helper. Display **No data** when the source has no sample. The stable and development implementations differ in how they handle non-finite numeric inputs. `card_severity($value)` normalizes a widget severity. The aliases `up` and `good` select green by default. `warn`, `warning`, and `recovering` select warning styling. `down`, `bad`, and `error` select error styling. Other values use `none`. For a card header, set `data-severity` to the normalized token. Pair the color with a label such as **2 down**. ## Grid, controls, and themes - Give each card a unique, stable string in `data-card`. The controller uses that ID to match a refresh to the live card and to serialize order. Keep the grid's direct children in reading order. Put toolbars outside it. - Set `--cc-cols` on the grid to choose a column count (default 4). The width classes run from `.ccW1` to `.ccW8`. At narrow breakpoints, use a plugin stylesheet to reduce both column count and card spans. - Use `data-expandable="1"` for a card with more content than its preview. The controller synchronizes `data-expanded` and `.ccCardExpanded`. The stylesheet clips the collapsed body at 210 CSS pixels. Include both expand and collapse buttons so keyboard focus can move between them. - For stepped resizing, set `data-size-model="steps"`, a numeric `data-height`, and a matching `.ccH1`, `.ccH2`, or `.ccH3` class. Implement the size limits in your adapter. Return markup with the new class and height together so the saved state matches the visible layout. - Use focusable buttons for `.ccDrag` and `.ccTool`. Give each icon-only button an accessible name. On the handle, Left or Up moves one position earlier, and Right or Down moves one later. - Set theme variables on the grid to scope them to the dashboard. Examples include `--cc-card`, `--cc-text`, `--cc-border`, `--cc-header-bg`, `--cc-header-fg`, and `--cc-sev-warn`. Check text and controls against their background in a light and a dark theme. ## Adapter reference Pass an object as the second argument to `CactiCards.init(grid, adapter)`. Initialization runs once per grid element. If Cacti replaces the entire grid during navigation, initialize the new element after inserting it. | Member | When it runs and what to return | | --- | --- | | `cardSelector`, `idAttr` | Override the controller's card selector and ID attribute. The defaults are `.ccCard` and `data-card`. Keep the shared CSS classes when using the core stylesheet. | | `fetchCard(id, state)` | Refresh one card. Return its complete HTML or a promise for it. State contains `expanded` and `height`. A null result leaves the markup in place. | | `onRefresh(id, card)` | Takes precedence over `fetchCard`. Use this when the plugin replaces only the body. The host owns completion, ordering, and error feedback on this path. | | `onResize(id, direction, card)` | A grow or shrink button was activated. Return replacement HTML, directly or through a promise, or update the live card in the callback. | | `maximize(id, mode, card)` | Open a host-provided detail view. Mode comes from `data-maximize` and defaults to `body`. Manage dialog focus and return it when the dialog closes. | | `addControl`, `onAddCard(id)` | Supply a select element or its DOM ID. On change, return the new card's complete HTML or a promise. Use the empty option as the prompt. | | `onRemoveCard(id, card)` | Return a promise when removal must be confirmed by storage. Rejection keeps the card. Without a callback, removal updates the current grid only. | | `onLayoutChange(state)` | Receives the current order, expanded flags, and heights after a layout change. Calls are debounced by 250 ms. The host chooses storage and handles write failures. | | `applyTheme(grid)` | Set host-specific theme variables. Runs on initialization and when the controller adds or replaces a card. | For controller-managed replacement, a refresh requested during a resize waits for that card's resize to finish. If a user toggles expansion during a pending refresh, the controller preserves the live choice when the returned card can still expand. Keep scripts and event handlers in your plugin JavaScript when returning a fragment. Render user-visible data with the same authorization and escaping as the initial page. ## Save and restore a layout With the example grid open, run the following in the browser console. ```javascript const grid = document.getElementById('carddemo-grid'); CactiCards.serialize(grid, {}); ``` After the reorder and expansion above, the result has this shape. ```json { "order": ["devices", "load"], "cards": { "devices": { "expanded": false, "height": 1 }, "load": { "expanded": true, "height": 1 } } } ``` To retain changes across visits, add `onLayoutChange` to the adapter passed during the original initialization. Save a user's layout under that user's account and dashboard ID. For server storage, use Cacti's authenticated request and CSRF handling for writes. Allow only authorized card IDs, discard duplicates, and validate heights against each card's limits. On the next visit, intersect the saved order with the current catalogue. Decide where newly available cards belong. Render cards in that order and apply the saved `data-expanded`, `data-height`, and size class **before** calling `init`. Pass the same adapter to `serialize` if you customized the selector or ID attribute. For a host that inserts cards itself, `CactiCards.bindCard(grid, adapter, card)` wires a newly attached card. `CactiCards.replaceCard(grid, adapter, oldCard, html)` replaces one card, binds it, reapplies the theme callback, and returns the new element or null. Keep the same stable ID across a replacement. ## Verify and troubleshoot | Symptom | Check | | --- | --- | | Values appear but buttons do nothing | Confirm the page loaded `cards.js`, the grid exists when initialized, and each tool has the `ccTool` class and its `data-tool` action. | | Expand has no visible effect | Check `data-expandable`, the `ccCardBody` wrapper, and whether the contents exceed the collapsed height. | | Grow does not change height | Confirm the steps model, the adapter's size calculation, and the matching row class and numeric height in the response. | | Refresh shows the login page or a whole dashboard | Inspect the response after signing in again. The fragment route must return exactly one authorized card with the requested ID. | | A layout reverts after reloading | Inspect the saved state and verify that the next full-page render restores it before initialization. | Test keyboard reordering, expansion during a slow refresh, and a failed refresh with the browser open. Verify that keyboard focus follows the move handle and that a failed refresh preserves the existing content. If your plugin saves layouts, also test reload, a removed card ID, and two users with different permissions. ## Implementation references - [PHP widgets and page assets on develop][php-dev] - [PHP widgets and page assets on 1.2.x][php-stable] - [JavaScript controller and adapter implementation][controller] - [Card layout and control styles][chrome] - [Widget markup styles][widgets] - [Controller regression tests][tests] [ip-shot]: images/card-api-intropage.png [ip-api]: [apc-host]: [mac-host]: [sys-host]: [hmib-host]: [topx-host]: [alarm-host]: [ip-mac]: [ip-misc]: [ip-thold]: [ip-sys]: [ip-monitor]: [overview]: images/card-api-overview.png [expanded]: images/card-api-expanded.png [php-dev]: [php-stable]: [controller]: [chrome]: [widgets]: [tests]: --- Copyright (c) 2004-2026 The Cacti Group