Build a Custom Field
This guide builds a field that offers the brand colors of your site. Editors click a swatch to pick one. On the way, it covers what the short example in Custom fields skips: following changes, read-only forms, data from the server, texts in both admin languages, styles, and a description that follows the value.
Before you start
- Read Custom fields for
custom:types and.client.tsmodules. - The input is a Vue component. Nuxt compiles
.vuefiles. In Astro, add@astrojs/vue. With React, write the same component in JSX and userenderReact().
Build the field
Store the colors
Editors keep the brand colors in a global on the Settings page:
import { defineGlobal } from "tenoncms";
export const brand = defineGlobal({
label: "Brand",
nav: { display: "settings" },
fields: {
colors: {
type: "array",
fields: {
name: { type: "text", required: true },
hex: { type: "text", required: true },
},
},
},
});
Add it to globals: { brand } in tenon.config.ts.
Write the component
The component gets the field context as props. data holds the colors, which the next steps load:
<script setup lang="ts">
import type { FieldContext } from "tenoncms/admin";
defineProps<FieldContext<{ name: string; hex: string }[]>>();
</script>
<template>
<div class="brand-color">
<button
v-for="color in data"
:key="color.hex"
type="button"
class="brand-color__swatch"
:style="{ background: color.hex }"
:title="color.name"
:aria-label="color.name"
:aria-pressed="value === color.hex"
:disabled="field.readOnly"
@click="onChange(value === color.hex ? null : color.hex)"
/>
</div>
</template>
<style scoped>
.brand-color {
display: flex;
gap: 0.5rem;
}
.brand-color__swatch {
width: 2rem;
height: 2rem;
border-radius: 9999px;
}
.brand-color__swatch[aria-pressed="true"] {
outline: 2px solid currentColor;
outline-offset: 2px;
}
</style>
- A click on the selected swatch clears the value.
- The component gets new props on every change: a new value, a read-only form or new colors.
- The styles are scoped. Unscoped CSS would change the whole admin. See Styles and UI libraries.
Turn it into a mount function
renderVue() makes the component the input:
import { renderVue } from "tenoncms/admin/vue";
import BrandColor from "./BrandColor.vue";
export const mountBrandColor = renderVue(BrandColor);
Register it with a load
load runs on the server, and the component gets its result as data:
import { mountBrandColor } from "./src/admin/brand-color.client";
export default defineCms({
// ...
admin: {
fields: {
brandColor: {
mount: mountBrandColor,
load: async ({ cms }) => {
const { colors } = await cms.getGlobal("brand");
return (colors ?? []).map(({ name, hex }) => ({ name, hex }));
},
},
},
},
});
loadgets the signed-inuser, theircms, the adminlocale, thefieldand itspath.ownernames the document or global that holds the field.loadruns when the field mounts and when its owner changes, not when the value changes.- It runs when the field mounts, and again when the owner changes, like when a new document gets its id. It does not run while the editor types.
- It MUST only read, and MUST return JSON.
Use it in a field
color: { type: "custom:brandColor", label: "Color" },
Translate the texts
Text you show yourself needs both admin languages. translator() reads your own message files, and tenon.locale is the language of the editor:
<script setup lang="ts">
import { computed } from "vue";
import { translator, type FieldContext } from "tenoncms/admin";
import de from "./locales/de.json";
import en from "./locales/en.json";
const props = defineProps<FieldContext<{ name: string; hex: string }[]>>();
const t = computed(() => translator({ en, de }, props.tenon.locale));
</script>
<template>
<p v-if="!data.length">{{ t("brandColor.empty") }}</p>
<!-- the swatches -->
</template>
Show the name under the field
A field's description can be a function from a .client.ts module. It runs in the browser on every change, with the unsaved value:
import type { FieldDescription } from "tenoncms/admin";
export const colorDescription: FieldDescription<string | null> = ({ value }) =>
value ? `Selected: ${value}` : "Pick a brand color";
import { colorDescription } from "./products.client";
// ...
color: { type: "custom:brandColor", label: "Color", description: colorDescription },
- It also gets
data(the whole document),siblings(the fields next to it),pathandlocale. - It MUST be synchronous. Return
nullto hide the description.
Without a framework
In plain DOM, return { update, unmount } to follow changes. update gets the new context:
import type { FieldContext, Mount } from "tenoncms/admin";
type Colors = { name: string; hex: string }[];
export const mountBrandColor: Mount<FieldContext<Colors>> = (el, ctx) => {
const render = ({ data, value, field, onChange }: FieldContext<Colors>) =>
el.replaceChildren(
...data.map((color) => {
const swatch = Object.assign(document.createElement("button"), {
type: "button",
title: color.name,
disabled: field.readOnly,
onclick: () => onChange(value === color.hex ? null : color.hex),
});
swatch.style.cssText = `width: 2rem; height: 2rem; border-radius: 9999px; background: ${color.hex}`;
swatch.setAttribute("aria-pressed", String(value === color.hex));
return swatch;
}),
);
render(ctx);
return { update: render, unmount: () => el.replaceChildren() };
};
Related resources
- Custom fields: the basics.
- Browser modules:
.client.tsmodules andclientRef(). - Write a plugin: ship the field to other projects.
- The example plugin's
ratingfield, in plain DOM, Vue and React. See Plugins.