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.
| 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.
Download the example plugin 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]
name = carddemo
version = 1.0
longname = Card API Example
author = Example Maintainer
homepage = https://www.cacti.net
compat = 1.2.32Register the page as a realm so the full dashboard and the refresh response use the same Cacti permission check.
<?php
function plugin_carddemo_version() {
$info = parse_ini_file(__DIR__ . '/INFO', true, INI_SCANNER_RAW);
return $info['info'];
}
function plugin_carddemo_install() {
api_plugin_register_realm('carddemo', 'dashboard.php',
'View Card API Example', 1);
}The page can return the whole grid or one card. Both paths call the same renderer, which keeps the card ID, controls, and markup consistent. Only the two IDs in the catalogue select content.
<?php
chdir(dirname(__DIR__, 2));
require_once './include/auth.php';
$titles = [
'load' => __('Poller load', 'carddemo'),
'devices' => __('Device availability', 'carddemo'),
];
function carddemo_render($id, $title, $expanded) {
$load = $id === 'load';
?>
<section class="ccCard ccW2" data-card="<?= html_escape($id) ?>"
data-severity="<?= $load ? 'warn' : 'up' ?>"
data-expandable="<?= $load ? '1' : '0' ?>"
data-expanded="<?= $load && $expanded ? '1' : '0' ?>" data-height="1">
<header class="ccCardHeader">
<button type="button" class="ccDrag"
aria-label="<?= __esc('Move %s', $title, 'carddemo') ?>">↕</button>
<h2 class="ccTitle"><?= html_escape($title) ?></h2>
<span class="ccTools">
<?php if ($load) { ?>
<button type="button" class="ccTool" data-tool="expand">
<?= __esc('Show more', 'carddemo') ?></button>
<button type="button" class="ccTool" data-tool="collapse">
<?= __esc('Show less', 'carddemo') ?></button>
<?php } ?>
<button type="button" class="ccTool" data-tool="refresh">
<?= __esc('Refresh', 'carddemo') ?></button>
</span>
</header>
<div class="ccCardBody">
<?php
if ($load) {
print card_gauge(72, '72%', __('Cycle budget used', 'carddemo'), 'warn');
print card_bullet(12, 24, 42, __('Cycle duration', 'carddemo'),
__('12 / 24 / 42 seconds', 'carddemo'), 'warn', 0, 60);
print card_bar(80, __('Worker utilization: 80%', 'carddemo'), 'up');
print card_stat('18', __('Idle workers', 'carddemo'));
} else {
print card_stat('48 / 50', __('Devices responding', 'carddemo'));
print card_stackbar([
['percent' => 96, 'severity' => 'up', 'label' => __('48 up', 'carddemo')],
['percent' => 4, 'severity' => 'down', 'label' => __('2 down', 'carddemo')],
], true);
}
?>
</div>
</section>
<?php
}
if (isset($_GET['card'])) {
$id = $_GET['card'];
if (!is_string($id) || !isset($titles[$id])) {
http_response_code(404);
exit;
}
carddemo_render($id, $titles[$id], ($_GET['expanded'] ?? '') === '1');
exit;
}
top_header();
?>
<div id="carddemo-grid" class="ccGrid">
<?php foreach ($titles as $id => $title) {
carddemo_render($id, $title, false);
} ?>
</div>
<p id="carddemo-message" role="status"
data-failure="<?= __esc('Refresh failed. Reload the page and try again.', 'carddemo') ?>"></p>
<?php
print get_md5_include_js('plugins/carddemo/dashboard.js');
bottom_footer();The controller passes the current expanded state to the refresh callback. Send that state to the same authenticated PHP page and return the outer HTML of one card. The example reports a failed refresh next to the grid. Use the Cacti URL path for the endpoint so refresh works when Cacti is installed in a subdirectory.
(function () {
const grid = document.getElementById('carddemo-grid');
const message = document.getElementById('carddemo-message');
if (!grid) {
return;
}
CactiCards.init(grid, {
async fetchCard(id, state) {
const url = new URL('plugins/carddemo/dashboard.php',
new URL(urlPath, window.location.origin));
url.searchParams.set('card', id);
url.searchParams.set('expanded', state.expanded ? '1' : '0');
try {
const response = await fetch(url);
if (!response.ok || response.redirected) {
throw new Error('Card unavailable');
}
const html = await response.text();
const fragment = document.createElement('template');
fragment.innerHTML = html.trim();
const card = fragment.content.firstElementChild;
if (!card || !card.matches('.ccCard') || card.dataset.card !== id) {
throw new Error('Unexpected card response');
}
message.textContent = '';
return card.outerHTML;
} catch (error) {
message.textContent = message.dataset.failure;
throw error;
}
}
});
})();From the Cacti root, use the same account you normally use to manage plugins and run the following command.
php cli/plugin_manage.php --plugin=carddemo --install --enableSign in with View Card API Example and open
plugins/carddemo/dashboard.php under your Cacti URL. Focus the move
button on Device availability and press Left. Select Show more on
Poller load to reveal Idle workers, then select Refresh.
The expanded card should stay open and the device card should stay first.
Reloading the full page restores the initial order in this example.
Intropage supplies the grid, header, permissions, refresh schedule, and dashboard picker. Your plugin registers a panel and renders its body. The same PHP widget can appear in your own dashboard and in Intropage. Give the panel its own ID so users can configure each dashboard separately.
The example archive includes an optional provider for Intropage. The standalone dashboard still works without Intropage. With the example and Intropage enabled, run this from the Cacti root:
php plugins/carddemo/register-panel.phpExpect Registered carddemo_capacity. In Console > 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.
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:
$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.
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:
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
for individual enable, disable, update, and removal calls.
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 |
| 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 |
| 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 |
| Syslog | Extend the status dashboard's card definitions and renderer. Preserve its filters when fetching refreshed markup. Syslog dashboard |
| TopX | Extend the overview catalog and select the records for the requested timespan. Its adapter can refresh the body in place. TopX dashboard |
| 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 |
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 |
| Syslog | Details, top devices and message levels. Syslog panels |
| Thold | Threshold status and recent threshold events. Threshold panels |
| Maint | Maintenance schedule details. Maintenance panel |
| Webseer | Webseer checks for installations using this plugin. Webseer panel |
| Servcheck | Service-check details. Servcheck panel |
| Monitor | The Analyze panel can report devices missing monitoring when Monitor is enabled. This is part of the existing analysis panel. Analyze panel |
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.
- 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-colson the grid to choose a column count (default 4). The width classes run from.ccW1to.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 synchronizesdata-expandedand.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 numericdata-height, and a matching.ccH1,.ccH2, or.ccH3class. 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
.ccDragand.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.
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.
With the example grid open, run the following in the browser console.
const grid = document.getElementById('carddemo-grid');
CactiCards.serialize(grid, {});After the reorder and expansion above, the result has this shape.
{
"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.
| 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.
- PHP widgets and page assets on develop
- PHP widgets and page assets on 1.2.x
- JavaScript controller and adapter implementation
- Card layout and control styles
- Widget markup styles
- Controller regression tests
Copyright (c) 2004-2026 The Cacti Group


