A Layout Editor widget has a PHP data contract and a React component. The PHP schema also describes the settings an administrator can edit.
This chapter uses the CatalogService from Call a third-party API.
Add the PHP widget
Create Widgets/CatalogWidget.php in your addon. Use the namespace MyCustom\Catalog\Widgets and extend Vanilla\Widgets\React\ReactWidget.
The following is a class outline. The schema and data methods are shown in the next steps.
class CatalogWidget extends ReactWidget
{
public static function getWidgetID(): string
{
return "my-custom-catalog.catalog";
}
public static function getWidgetName(): string
{
return "My Custom Catalog";
}
public static function getComponentName(): string
{
return "MyCustomCatalog";
}
public static function getWidgetIconPath(): ?string
{
return null;
}
// Constructor, getWidgetSchema() and getProps() follow below.
}
The base class provides a default widget group and supported layout sections. Override those when your widget needs different placement.
Keep MyCustomCatalog consistent across PHP, the runtime component registration and the editor preview.
Add this constructor. It preserves the inspected base class's dependencies:
// Imports: FragmentModel from Vanilla\Dashboard\Models,
// TwigFragmentRenderer from Vanilla\Web,
// CatalogService from MyCustom\Catalog\Library.
public function __construct(
FragmentModel $fragmentModel,
TwigFragmentRenderer $twigRenderer,
private CatalogService $catalog,
private \Gdn_Session $session
) {
parent::__construct($fragmentModel, $twigRenderer);
}
Confirm the parent constructor against your target LTS before adapting this outline.
Describe the administrator settings
Add getWidgetSchema(). The method excerpt below uses Garden\Schema\Schema and the classes FormOptions, SchemaForm and StaticFormChoices from Vanilla\Forms.
public static function getWidgetSchema(): Schema
{
return Schema::parse([
"title:s" => [
"default" => "Resource catalog",
"x-control" => SchemaForm::textBox(new FormOptions("Title")),
],
"query:s" => [
"default" => "",
"maxLength" => 200,
"x-control" => SchemaForm::textBox(new FormOptions("Initial search")),
],
"defaultSort:s" => [
"default" => "title",
"enum" => ["title", "newest"],
"x-control" => SchemaForm::dropDown(
new FormOptions("Default sort"),
new StaticFormChoices(["title" => "Title", "newest" => "Newest"])
),
],
"pageSize:i" => [
"default" => 10,
"minimum" => 1,
"maximum" => 30,
"x-control" => SchemaForm::textBox(new FormOptions("Page size"), "number"),
],
]);
}
The schema controls allowed values. x-control describes the editor control. These are administrator defaults; members will change their own search, sort and page after the widget renders.
Load the first page
Add getProps(). Import Garden\Web\Exception\ServerException.
public function getProps(): ?array
{
if (!$this->session->isValid()) {
return null;
}
$params = [
"q" => $this->props["query"],
"sort" => $this->props["defaultSort"],
"page" => 1,
"limit" => $this->props["pageSize"],
];
try {
$page = $this->catalog->fetchPage($params);
$error = null;
} catch (ServerException $exception) {
$page = null;
$error = "The catalog is unavailable.";
}
return [
"title" => $this->props["title"],
"initialParams" => $params,
"initialPage" => $page,
"initialError" => $error,
];
}
Returning null hides the widget for the signed-out audience in this example. The endpoint separately enforces authentication.
An upstream failure returns an error state instead of a successful empty list. Keep credentials and exception details out of these props.
The base widget returns no default SEO HTML when it has no fragment renderer. Add an escaped, equivalent server-rendered representation if your project requires crawlable results. React data preloading alone does not create that HTML.
Register the widget
Add this to CatalogContainerRules::configureContainer():
// Imports: Vanilla\Layout\LayoutHydrator,
// MyCustom\Catalog\Widgets\CatalogWidget.
$container->rule(LayoutHydrator::class)->addCall("addReactResolver", [CatalogWidget::class]);
Pass the class name as a string. In the inspected implementation, addReactResolver() accepts a class name and creates the widget through the container when a layout is hydrated. Do not wrap it in a container Reference; that supplies an instance instead of a class name.
This registers the PHP resolver and catalog metadata. It does not register the React component.
Create src/scripts/widgets/CatalogWidget.tsx with a default-exported component. Register it in src/scripts/entries/layouts.tsx:
import { registerLoadableWidgets } from "@library/utility/componentRegistry";
registerLoadableWidgets({
MyCustomCatalog: () => import("../widgets/CatalogWidget"),
});
The two registrations are separate. The PHP resolver lets Layout Editor list the widget, save its settings and produce its props. The frontend registration lets the community page render those props.
Layout Editor can therefore offer a widget that the community page cannot yet render. The page needs a built Layouts entry that registers MyCustomCatalog. If you have not passed the Layouts entry checkpoint, complete it before placing the widget.
Fetch again when a member interacts
Define the props used by the component. These are tutorial types matching the PHP result:
type CatalogParams = {
q: string;
sort: "title" | "newest";
page: number;
limit: number;
};
type CatalogPage = {
items: Array<{ id: string; title: string; url: string }>;
page: number;
hasMore: boolean;
};
type CatalogWidgetProps = {
title: string;
initialParams: CatalogParams;
initialPage: CatalogPage | null;
initialError: string | null;
};
The following component excerpt shows the data flow. Add the controls and rendering described below.
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import apiv2 from "@library/apiv2";
export default function CatalogWidget(props: CatalogWidgetProps) {
const [params, setParams] = useState(props.initialParams);
const isInitial =
params.q === props.initialParams.q &&
params.sort === props.initialParams.sort &&
params.page === props.initialParams.page &&
params.limit === props.initialParams.limit;
const query = useQuery<CatalogPage>({
queryKey: ["myCustomCatalog/codeDeploy", params],
queryFn: async () => {
const response = await apiv2.get("/my-custom-catalog", { params });
return response.data;
},
initialData: isInitial ? props.initialPage ?? undefined : undefined,
enabled: !isInitial || !props.initialError,
staleTime: 60_000,
retry: false,
});
// Render the controls, status and results described below.
// Search and sort: setParams({ ...params, q, sort, page: 1 }).
// Next: setParams({ ...params, page: params.page + 1 }).
}
The community API client supplies the API v2 prefix. The React Query key includes every request parameter.
Supply the initial page only for the query that produced it. Otherwise a new search can briefly show the old page as its initial result.
If preload failed, this example waits for a member action or a Retry button calling query.refetch(). It does not immediately repeat the failed preload request.
The one-minute browser freshness window is an example setting. It is separate from the two-minute PHP response cache.
Add the controls and result states
Use a labelled search input with a maximum length of 200. Provide Title and Newest sort options. Submit the search deliberately, and reset the page to 1 whenever search or sort changes.
Keep Previous disabled on page 1. Keep Next disabled when hasMore is false or a page request is running. Handle a final page that contains no results without advancing again.
While loading, display a short status message. If a request fails, show a helpful error and a Retry action. An empty successful response should say that no results match the search.
Keep controls visible in these states so members can change their query. If you retain old results during refetch, label them as updating. Render text through React and validate link URLs before using them.
Use Vanilla's t() helper for interface text in plugin React code. In Widget Builder, use Utils.t(). The compact snippets use literal labels to keep the data flow easy to follow.
Provide an editor preview
Create CatalogWidgetPreview.tsx beside the component. Render the same UI with fixed catalog data and disable live requests in preview mode.
An abbreviated preview might be:
export function CatalogWidgetPreview(props: CatalogWidgetProps) {
return <CatalogPresentation title={props.title} page={samplePage} />;
}
CatalogPresentation and samplePage are components/data you create in the addon. Keep the preview independent of credentials and the external API.
Register the preview in entries/admin-new.tsx:
import { registerWidgetOverviews } from "@dashboard/layout/overview/LayoutOverview";
import { CatalogWidgetPreview } from "../widgets/CatalogWidgetPreview";
registerWidgetOverviews({ MyCustomCatalog: CatalogWidgetPreview });
Rebuild. Add My Custom Catalog to a layout, set its defaults, and save the layout. Open a page assigned to that layout and test as an ordinary signed-in member.
Find why a placed widget does not load
A placed widget can fail in two different places. Check the browser console first.
If the console reports "MyCustomCatalog" cannot be found in the component registry, the page received the widget's props but no component is registered under that name. The widget area shows There was a problem loading "MyCustomCatalog".
In that case, the problem is in the frontend. Confirm that getComponentName() returns exactly the key passed to registerLoadableWidgets(). Restore the temporary console message from chapter 1 and confirm that it appears on the same page. If it does not, rebuild or restart the development build, then reload the page. Refreshing the addon cache alone will not fix it.
If the component renders but shows your error state, the frontend is working. The problem is in the first-page fetch. Request /api/v2/my-custom-catalog with the widget's default settings as its parameters. Then check the upstream response, credentials and provider limits described in Call a third-party API.