Skip to main content
Version: v1 (Current)

Collections API — GXP Plugin Guide

How to use the Collections API from a GXP plugin. Covers dependency setup, CRUD, relationships, assets, filtering, constraints, and dynamic form rendering.

Setup​

1. Declare catalog-supported dependencies​

In the intended App version, open Settings → Dependencies and use the current Collection/CollectionEntry/CollectionAsset catalog. Permission names are specific actions, not a universal :viewAny suffix convention. The catalog's Collection slot exposes view_collections, entry read/manage and asset read/manage actions; child slots have their own actions. Grant only the operations required by the App.

This is a minimal read-oriented declaration fragment inside app-manifest.json, not a complete entry/asset write authorization plan:

Use the standard App scaffold’s @/stores/gxpPortalConfigStore import so the production bundle uses the installed host store. The reviewed AI scaffold’s @gx-runtime variant can bundle a separate local store; do not substitute it.

{
"dependencies": [
{
"model": "Collection",
"identifiers": ["content_collection"],
"permissions": ["view_collections", "view_collection_entries"],
"visibleFields": []
}
]
}

Expose a configuration dependency selector using the same content_collection identifier, install the App and bind the intended project collection. A declaration does not itself supply a record binding. Collection route identity is its slug; verify the persisted selector value, resolver key and operation path agree rather than substituting a numeric ID by habit.

Entry and asset writes need the corresponding catalog-supported grants and correct parent scope. The old example's three broad declarations are not universally required or sufficient. For child/parent scopes, advanced permissionKey/parentRelation declarations and the visual editor's preservation limits, follow Permissions and Dependencies. Test excluded collections/projects and audience contexts as well as a successful request. An empty visibleFields array inherits available scope; it is not field redaction.

2. Initialize the supplied store​

Mount inside the existing runtime application/store context:

import { useGxpStore } from "@/stores/gxpPortalConfigStore"

const store = useGxpStore()

Prefer store.callApi(operationId, dependencyIdentifier, data) with the deployed catalog's actual operation ID and matching bound identifier. It resolves operation metadata and page/project context; an unknown operation or unresolved required path parameter fails. The runtime integration guide describes this adapter boundary. A helper call still depends on operation grants, project ownership and audience rules.

3. Direct transport paths when needed​

The lower-level examples below assume initialized store.pluginVars.projectId contains teamSlug/projectSlug, a compatible project API host/proxy and the App's page/principal context. They do not resolve a bound collection automatically or grant access. Reject missing context rather than sending a path containing empty or undefined slugs:

function basePath() {
const parts = String(store.pluginVars?.projectId || "").split("/")
if (parts.length !== 2 || parts.some((part) => !part.trim())) {
throw new Error("Collection API requires teamSlug/projectSlug context")
}
const [teamSlug, projectSlug] = parts.map(encodeURIComponent)
return `/api/v1/projects/${teamSlug}/${projectSlug}/collections`
}

The runtime's configured API base is a host or host-mapping proxy; do not infer the request prefix by testing whether a configuration string ends in /api. Select a slug from the bound/authorized collection, and encode any dynamic path segment before adding it to a custom path.

Shared store methods​

MethodSignatureResult
callApi(operationId, identifier, data)Catalog operation using runtime context/bindings
apiGet(endpoint, params)GET response body
apiPost(endpoint, data)POST response body
apiPut(endpoint, data)PUT response body
apiDelete(endpoint)DELETE response body

The current toolkit adds an apiPatch helper for development, but the platform store does not expose it. Do not rely on that extra as a shared plugin contract. The update examples below use POST method override with _method: "PATCH"; verify that transport against the deployed endpoint, or use the catalog operation's declared PATCH method. This is not a claim that method override works in every host/version.

The direct helpers return response.data from the HTTP client and wrap errors in a new Error containing method/path/message. Do not assume they preserve Axios error.response or return an already-unwrapped resource. Inspect the actual response envelope and use the server's returned ID, pagination and validation structure for the selected operation. The remaining payload/response examples below require their field schema, grants and runtime acceptance checks.

All examples use a slug representing the selected collection, such as sponsors. Collection definition list/detail/search are registered in the versioned API; design creation/update belongs to separate dashboard workflows.

Collections​

// List all collections
const result = await store.apiGet(`${basePath()}`)

// Get one collection (by slug) with field definitions
const collection = await store.apiGet(`${basePath()}/${slug}`, {
include: "fieldDefinitions", // also: "sections", "formLayouts"
})

// Search collections
const result = await store.apiPost(`${basePath()}/search`, {
search: { value: "sponsor" },
filters: [{ field: "status", value: "active" }],
})

Filterable: status, name, slug — Searchable: name, slug, description — Sortable: name, created_at, status


Entries​

List​

const result = await store.apiGet(`${basePath()}/${slug}/entries`, {
limit: 50,
page: 1,
sort: "data->year", // prefix with data-> for JSONB fields
populate: "venue", // resolve relationship fields
})
// result.data = entries array, result.meta = { total, current_page, last_page }

Pagination: limit defaults to 100 (max 200), page defaults to 1.

Show​

const entry = await store.apiGet(`${basePath()}/${slug}/entries/${id}`)

Show auto-populates all relationship fields. Use populate: "none" to skip.

Create​

const entry = await store.apiPost(`${basePath()}/${slug}/entries`, {
data: {
name: "Acme Corp",
tier: "gold",
venue: 42, // belongs_to: integer ID
tags: [1, 5, 12], // belongs_to_many: array of IDs
},
})

Update​

const entry = await store.apiPost(`${basePath()}/${slug}/entries/${id}`, {
_method: "PATCH",
data: { tier: "platinum" }, // partial update — only changed fields
})

Delete​

await store.apiDelete(`${basePath()}/${slug}/entries/${id}`)

Search & Filter​

Use the POST search endpoint with explicit filters. The entry controller adds data->{slug} to its filter whitelist when that field is marked is_searchable, and to the sort whitelist when is_sortable. System filters include status, created_at, updated_at, submitted_by_id and submitted_by_type; system sort fields are status, created_at and updated_at. Field flags control accepted query inputs, not authorization or read visibility.

For this example, define name as searchable/sortable and tier as searchable in the selected collection. The collection-definition controller configures full-text fields, but the entry controller inherits Orion's empty searchableBy() list; do not assume search: { value: ... } searches all entry JSON. Use the explicit named-field filter below:

const result = await store.apiPost(`${basePath()}/${slug}/entries/search`, {
filters: [
{ field: "data->name", operator: "ilike", value: "%Acme%" },
{ field: "data->tier", operator: "=", value: "gold" },
{ field: "status", operator: "=", value: "draft" },
],
sort: [{ field: "data->name", direction: "asc" }],
})

Use ilike — like is case-sensitive on PostgreSQL:

{ field: "data->name", operator: "ilike", value: "%acme%" }

Nested AND/OR​

{
filters: [{
type: "or",
nested: [
{ field: "data->tier", operator: "=", value: "gold" },
{ field: "data->tier", operator: "=", value: "platinum" },
],
}]
}

Sort via GET​

store.apiGet(`${basePath()}/${slug}/entries`, { sort: "-data->year" }) // - prefix = descending

Only fields marked is_sortable plus status, created_at, updated_at.


Batch Operations​

Batch endpoints are registered, but request shape and write recovery matter. The current platform sets orion.transactions.enabled to false. Orion's outer batch transaction hooks therefore do not wrap the whole operation; the entry service's individual transactions do not make the entire batch atomic. A later validation/permission/write failure can follow earlier committed items. Read back IDs/state after interruption or rejection before retrying, and do not blindly replay creates. External side effects and deployed concurrency need separate tests.

Batch Create​

Each resource carries its own nested data and must satisfy the collection schema/layout and submitter constraints. Replace sample values with configured field options.

await store.apiPost(`${basePath()}/${slug}/entries/batch`, {
resources: [
{ data: { name: "Entry 1", tier: "gold" } },
{ data: { name: "Entry 2", tier: "silver" } },
],
})

Batch Update​

await store.apiPost(`${basePath()}/${slug}/entries/batch`, {
_method: "PATCH",
resources: {
"101": { data: { tier: "platinum" } },
"102": { data: { tier: "platinum" } },
},
})

Orion resolves the target keys from this object and looks up each payload at resources.{entryId}. The older array of { id, data } objects is not this contract. Use IDs already verified under the selected parent; inspect returned resources rather than assuming every requested ID was found or changed.

Batch Delete​

await store.apiPost(`${basePath()}/${slug}/entries/batch`, {
_method: "DELETE",
resources: [101, 102, 103],
})

The sequential delete list is an ID list, unlike the update map. _method examples still require the deployed transport to accept method override; use the catalog method where appropriate. Successful database deletion does not certify external file cleanup or every event consumer.

Relationships & Population​

Writing​

TypeFormatExample
belongs_toInteger ID{ venue: 42 }
belongs_to_manyArray of IDs{ tags: [1, 5, 12] }
has_manyRead-onlyResolved from target FK

Populating on Read​

// Index — must name fields explicitly
store.apiGet(`${basePath()}/${slug}/entries`, { populate: "venue,speaker" })

// Nested (2-hop)
store.apiGet(`${basePath()}/${slug}/entries`, { populate: "venue.city" })

// Show — auto-populates all; use "none" to skip
store.apiGet(`${basePath()}/${slug}/entries/${id}`, { populate: "none" })

Do not use populate=* on index — returns 422.

Populated Shape​

Collection-entry targets are flat — their data fields are promoted to top level. Attendee and standard-model targets use their own serializers; do not assume every relationship target shares this shape:

entry.data.venue = {
id: 42,
collection_id: 5,
status: "draft",
created_at: "2026-06-08T19:50:09.000000Z",
name: "Main Hall", // data fields at top level
capacity: 500,
photo: 305, // file fields stay as IDs in sub-objects
}

PopulatedEntryResource excludes data keys id and collection_id before merging data over metadata. Other overlapping data names, including status or timestamps, can override the corresponding serialized metadata value. Do not use those flattened fields as authoritative lifecycle or authorization evidence. The stored target and its original data remain separate.

Population Limits​

LimitValue
Max depth3 hops
Max per has_many50 children per parent
Total populated-row budgetDefault 1,000; configurable via collections.max_populated_rows / COLLECTIONS_MAX_POPULATED_ROWS

meta.population_truncated is added when the population service reports truncation. Check it with the selected response envelope; do not assume an absent flag proves every target is accessible, present or fully expanded. Keep raw IDs separately when reconciliation requires them.


File Fields & Assets​

Write vs Read​

DirectionFormatExample
WriteInteger asset ID or null{ photo: 42 }
ReadResolved asset objectSee shape below

Asset Object Shape​

{
"id": 309,
"name": "booth-hero.jpg",
"original_name": "booth-hero.jpg",
"file_size": 204800,
"asset_url": "https://...",
"asset_thumbnail_url": "https://...",
"asset_medium_url": "https://...",
"asset_large_url": "https://...",
"mime_type": "image/jpeg",
"asset_class": "Gallery"
}

The current CollectionAsset original-URL accessor requests a 60-minute link; variant helpers can use different lifetimes. Local/unsupported storage adapters can return ordinary URLs rather than expiring signatures. Obtain URLs near use and verify their actual serving/expiry behavior instead of treating every property as a 60-minute private credential. Missing or unavailable variants can be null; confirm processing and stored outputs before displaying them. See upload URL boundaries.

Collection-entry target serialization retains file references from target data; it does not run the top-level asset resolver. A nested integer file ID is therefore not proof that a population depth limit was reached. Resolve and authorize that asset through the supported owning context before displaying it.

List Assets​

const assets = await store.apiGet(`${basePath()}/${slug}/assets`)

File Uploads​

The current callApi path detects explicit FormData and top-level Blob/File values, then uses multipart transport with its runtime auth and page-context headers. The linked integration guide has no submitMultipart() helper. Preserve the supplied runtime context rather than switching to a raw-fetch wrapper or copying a project credential.

For the catalog's actual asset-create operation and a dependency bound to the selected collection, an illustrative multipart payload is:

async function uploadCollectionAsset(operationId, dependencyIdentifier, file, assetClass) {
const body = new FormData()
body.append("file_name", file, file.name)
body.append("name", file.name)
body.append("asset_class", assetClass)
return await store.callApi(operationId, dependencyIdentifier, body)
}

file must be an actual user-selected File, and the operation/grants, class and collection binding must be valid. Explicit FormData preserves the chosen filename; the runtime's automatic Blob conversion can synthesize a filename. Do not set a multipart boundary header manually. The asset model's creation contract accepts file_name; the returned envelope, upload status, asset ID and required outputs must be checked before writing the entry reference.

This helper does not automatically select a direct-storage protocol, PUT a returned signed URL or wait for finalization/variants. Large/direct uploads require the owning endpoint's metadata/URL/finalization contract described in File Uploads and Storage. A successful metadata response or queued image job is not proof of completed bytes or usable variants.


Dynamic Form Rendering​

Fetch Field Definitions​

const response = await store.apiGet(`${basePath()}/${encodeURIComponent(slug)}`, {
include: "fieldDefinitions",
})
const collection = response.data // Standard resource envelope; verify the deployed response.
if (!collection || !Array.isArray(collection.field_definitions)) {
throw new Error("Collection response is missing included field definitions")
}
const fields = [...collection.field_definitions].sort((a, b) => a.order - b.order)

The resource includes field_definitions only when the relation is loaded; missing inclusion is not the same as a collection with no fields. Definitions alone do not supply the selected form layout, caller visibility rules, submission validation or a complete accessible renderer. Preserve normalized family/style semantics and validate through the owning API.

Field Definition Shape​

{
"slug": "tier",
"label": "Tier",
"field_type": "option-select",
"field_style": "select",
"is_required": true,
"is_searchable": true,
"is_sortable": true,
"options": [
{ "label": "Gold", "value": "gold" },
{ "label": "Silver", "value": "silver" }
],
"field_config": null,
"relationship_config": null,
"order": 1
}

Field Type to Input Mapping​

These are illustrative control mappings, not a complete form renderer. The platform definition generator also supplies layout placement, resolved defaults, file configuration and target-specific relationship selector metadata. Display-only content is presentation rather than an editable entry value.

field_typefield_styleRender As
inputtext<input type="text">
inputemail<input type="email">
inputnumber<input type="number">
inputtextarea<textarea>
option-selectselectSingle select using configured values/labels
option-selectcheckbox / select-multipleMulti-value selection; use the model's expected array format
booleanswitchToggle / checkbox
pickerdate-picker<input type="date">
pickerdatetime-picker<input type="datetime-local">
fileupload / asset-pickerFile input
relationshiprelationshipTarget-aware selector; has-many is computed/read-only
displaytype / other supported display stylesPresentation using field configuration; do not submit as editable data

Relationship Fields​

{
"target": "collection",
"type": "belongs_to",
"target_collection_id": 5,
"display_field": "name"
}
  • target: "collection" — search entries in the target collection
  • target: "attendee" — resolve the supported attendee context; field access still needs authorization
  • Current standard targets also include credential_type, group and agenda; use their target-specific selectors/serializers rather than a generic collection-entry request
  • type — belongs_to (single select), belongs_to_many (multi select), has_many (read-only)

Entry Constraints​

Constraints are configured in the admin dashboard (Collection Edit > Constraints tab) and enforced server-side on create/update.

ConstraintConfigApplies To
Uniquenessunique: [{ fields: ["tour"], scope: "submitted_by" }]Attendees only (when scoped)
Capacitycapacity: [{ field: "tour", max_field: "max_spots" }]All users
Max per submittermax_per_submitter: 2Attendees only

Admins bypass submitter-scoped constraints. Capacity applies to everyone.

Error Responses (422)​

Uniqueness — keyed to the first constrained data.{fieldSlug}; text uses the field label (here Tour):

{ "errors": { "data.tour": ["An entry with this Tour already exists."] } }

Capacity — keyed to data.{fieldSlug}:

{ "errors": { "data.tour": ["This selection has reached its capacity limit (2/2 spots taken)."] } }

Max per submitter — keyed to submission_limit:

{ "errors": { "submission_limit": ["You have reached the maximum of 2 entries for this collection."] } }

Handling 422 Errors​

The inspected direct apiPost helper wraps the underlying failure in a new Error and does not retain error.response.data.errors. The current callApi error wrapper preserves a numeric HTTP status when available, but also does not expose the complete validation map. Neither helper makes the server's example JSON above automatically available to a catch handler.

Keep entered values and show a recoverable validation message when the runtime reports rejection. If field-level server messages are required, implement and test an error-preserving adapter within the owning authenticated runtime/host integration; preserve page/principal headers and its normal credential handling. The linked runtime integration guide has no submitJson() implementation. Do not replace the supplied context with a copied project credential or assume raw fetch() is a drop-in authenticated equivalent. Reconcile saved state before retrying an interrupted write.


Submitted by and current-attendee filtering​

The entry API's write path passes the resolved request user to the service, which records submitter ID and model type when present. A client data.attendee field is application data, not evidence of who authenticated or permission to create on someone's behalf. Reader/page/guest and Attendee identities must not be conflated.

For a runtime that supplies an explicitly typed authenticated attendee, this client filter narrows a list by both polymorphic fields:

async function listMyEntries() {
const user = store.auth?.user
if (!user?.id || user.type !== "attendee") {
throw new Error("My entries requires a verified attendee identity")
}
return await store.apiPost(`${basePath()}/${encodeURIComponent(slug)}/entries/search`, {
filters: [
{ field: "submitted_by_id", operator: "=", value: user.id },
{ field: "submitted_by_type", operator: "=", value: "App\\Models\\Attendee" },
],
})
}

A runtime payload without that explicit type needs identity verification/normalization through its supported login contract before using this example. Do not fall back to the toolkit-only store.user member, infer an attendee from a reader's numeric ID, or send an undefined filter value. Both system submitter columns are exposed by the current entry filter whitelist.

This is a convenience query, not ownership enforcement: a caller can change or omit client filters. Server/page operation grants, parent collection scope and audience rules must authorize every returned row independently. Test another attendee with the same client code and a deliberately changed filter as an excluded case.


Entry Response Shape​

The following is a representative unwrapped entry object, not the complete HTTP response envelope or a promise that create/update responses run the read population hooks. Inspect the selected operation's data/metadata envelope before reading these fields. File objects shown here require the applicable read-time asset resolution and available outputs.

{
"id": 79947,
"collection_id": 370,
"project_id": 31,
"data": {
"name": "Acme Corp",
"tier": "gold",
"logo": {
"id": 305,
"name": "logo.png",
"original_name": "logo.png",
"file_size": 204800,
"asset_url": "https://...",
"asset_thumbnail_url": "https://...",
"asset_medium_url": "https://...",
"asset_large_url": "https://...",
"mime_type": "image/png",
"asset_class": "Gallery"
}
},
"submitted_by_type": "App\\Models\\Attendee",
"submitted_by_id": 28,
"status": "draft",
"created_at": "2026-06-08T19:50:09.000000Z",
"updated_at": "2026-06-08T19:50:09.000000Z"
}

User-defined fields live in entry.data.*. System fields (id, status, timestamps) are at the top level.


Gotchas​

IssueDetail
Entry pagination maxlimit caps at 200 — exceeding returns 422
No populate=* on indexReturns 422 — always name fields: ?populate=venue
Populated shape is flatData fields at top level: venue.name, not venue.data.name
File fields: read vs writeTop-level entry read hooks resolve assets; nested target files can remain IDs. Entry writes use IDs/null
Asset URLs expireOriginal helper requests 60 minutes; variants/fallback adapters differ; obtain fresh authorized URLs
PostgreSQL likeUse ilike for case-insensitive matching; %/_ retain SQL wildcard meaning
apiDelete has no bodyFor batch delete, use apiPost with _method: "DELETE"
Store may swallow 422 bodiesDirect helpers discard the validation map; current callApi preserves status only; an authenticated error adapter needs implementation/testing

Verification scope​

Source and document-reader review for these documented contracts is recorded in repository docs/collections-plugin-review-2026-10-14.md and docs/coverage/collections-plugin-source-snapshot.json. Canonical JavaScript checks exercise path validation, typed submitter filtering, captured batch envelopes, filename-preserving FormData and included field definitions without HTTP. Separate offline PHP fixtures exercise the actual Orion batch key parser/configuration (one case/five assertions) and populated-entry serializer (one case/six assertions). These scopes are not a full plugin or endpoint acceptance suite.

Verify the installed App's operation catalog, persisted bindings, page/principal headers and excluded-project/audience behavior on the target deployment. Test schema validation, missing/forbidden targets, population truncation, file uploads/finalization/variants, query behavior and interrupted/partially applied batches. A passing helper example does not certify routed authorization, browser behavior, provider output or concurrency.