Recipes

Build a Custom Field

A field input with server data, updates, translations and its own styles.

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.ts modules.
  • The input is a Vue component. Nuxt compiles .vue files. In Astro, add @astrojs/vue. With React, write the same component in JSX and use renderReact().

Build the field

Store the colors

Editors keep the brand colors in a global on the Settings page:

cms/globals/brand.ts
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:

src/admin/BrandColor.vue
<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:

src/admin/brand-color.client.ts
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:

tenon.config.ts
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 }));
        },
      },
    },
  },
});
  • load gets the signed-in user, their cms, the admin locale, the field and its path. owner names the document or global that holds the field.
  • load runs 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

cms/collections/products.ts
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:

src/admin/BrandColor.vue
<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>

See Texts in your own code.

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:

cms/collections/products.client.ts
import type { FieldDescription } from "tenoncms/admin";

export const colorDescription: FieldDescription<string | null> = ({ value }) =>
  value ? `Selected: ${value}` : "Pick a brand color";
cms/collections/products.ts
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), path and locale.
  • It MUST be synchronous. Return null to hide the description.

Without a framework

In plain DOM, return { update, unmount } to follow changes. update gets the new context:

src/admin/brand-color.client.ts
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() };
};