Skip to main content

Custom Fields

Tutorial: Slug Builder and Hero Image Picker

This tutorial builds two Recommended custom fields for a content type that already has a Title field (variable title):

  • URL Slug (urlSlug, required): fills itself from the title until the editor types their own, shows how many characters it uses out of 60, and turns red if it's still empty when the editor saves.
  • Hero Image (heroImage): lets the editor pick an image from dotCMS and shows a preview.

To add each field to the content type, follow Creating a Custom Field and paste the code below into Value. Check Required on the URL Slug field.

The content form after typing a title: URL Slug shows building-custom-fields-with-daisyui-tailwind with a Looks good badge and 44 / 60, and Hero Image shows a thumbnail and its /dA/ path.

URL Slug#


Value of the URL Slug field (urlSlug), set to Recommended:

<label id="urlSlug-control" class="input w-full">
  <span class="label">/blog/</span>
  <input id="urlSlug-input" type="text" class="grow" placeholder="my-first-article" autocomplete="off" />
</label>

<div class="flex items-center justify-between gap-2 mt-2">
  <div class="flex items-center gap-2">
    <span id="urlSlug-status" class="badge text-base-content/70">Empty</span>
    <span id="urlSlug-count" class="text-xs text-base-content/70">0 / 60</span>
  </div>
  <button id="urlSlug-generate" type="button" class="btn btn-sm btn-ghost">
    <i class="pi pi-sync"></i>
    <span>Generate from title</span>
  </button>
</div>

<script type="module">
  const MAX_LENGTH = 60;

  // Pure helper: it doesn't touch any field, so it can live outside ready().
  const slugify = (text) =>
    String(text || '')
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '')
      .toLowerCase()
      .trim()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-+|-+$/g, '');

  DotCustomFieldApi.ready(() => {
    // Get every field once, at the top of ready(), and reuse the reference.
    const slugField = DotCustomFieldApi.getField('urlSlug');
    const titleField = DotCustomFieldApi.getField('title');

    const control = document.getElementById('urlSlug-control');
    const input = document.getElementById('urlSlug-input');
    const status = document.getElementById('urlSlug-status');
    const count = document.getElementById('urlSlug-count');
    const generate = document.getElementById('urlSlug-generate');

    // Follow the title until the editor types a slug by hand.
    let editedByHand = Boolean(slugField.getValue());

    const render = (slug) => {
      const tooLong = slug.length > MAX_LENGTH;
      count.textContent = slug.length + ' / ' + MAX_LENGTH;
      status.textContent = !slug ? 'Empty' : tooLong ? 'Too long' : 'Looks good';
      status.className =
        'badge ' + (!slug ? 'text-base-content/70' : tooLong ? 'text-error' : 'text-primary');
    };

    const commit = (slug, options) => {
      input.value = slug;
      slugField.setValue(slug, options);
      render(slug);
    };

    // 1. Initial value: onChange doesn't fire for it, so read it once.
    input.value = slugField.getValue() || '';
    render(input.value);

    // 2. The editor types: keep the form in sync, normalise on blur.
    input.addEventListener('input', () => {
      editedByHand = true;
      slugField.setValue(input.value);
      render(input.value);
    });
    input.addEventListener('blur', () => commit(slugify(input.value)));

    // 3. Explicit action: derive the slug from another field.
    generate.addEventListener('click', () => {
      editedByHand = false;
      commit(slugify(titleField.getValue()));
    });

    // 4. React to another field. markDirty: false, because the editor didn't type it.
    titleField.onChange((title) => {
      if (!editedByHand) {
        commit(slugify(title), { markDirty: false });
      }
    });

    // 5. Paint the error state when the field is required and still empty after Save.
    slugField.onValidationChange((state) => {
      control.classList.toggle('input-error', state.invalid && state.touched);
    });
  });
</script>

What the Code Does#

  • class="input", badge, btn are daisyUI classes, so the field gets the editor's borders, colors and buttons without any CSS. See Styling Custom Fields.
  • <script type="module"> keeps this field's code separate from other custom fields on the same form, and ids start with the field's name (urlSlug-…) for the same reason.
  • DotCustomFieldApi.ready() wraps everything that touches the form. Inside it, each field is looked up once with getField().
  • getValue() reads what's already saved when the content opens.
  • setValue() saves a new value. The suggestion that follows the title passes { markDirty: false }, so it doesn't count as the editor changing the field.
  • onChange() runs code whenever another field changes, here the title.
  • onValidationChange() tells the field when it's invalid, so it can turn red. Checking touched waits until the editor has typed in the field or tried to save.

Hero Image#


Value of the Hero Image field (heroImage), set to Recommended:

<div class="flex items-center gap-3">
  <div class="size-16 rounded-box bg-base-200 overflow-hidden flex items-center justify-center">
    <img id="heroImage-preview" alt="" class="hidden size-16 object-cover" />
    <span id="heroImage-placeholder"><i class="pi pi-image text-base-content/50"></i></span>
  </div>
  <div class="flex flex-col gap-2 flex-1 min-w-0">
    <span id="heroImage-path" class="text-sm truncate text-base-content/70">No image selected</span>
    <div class="flex gap-2">
      <button id="heroImage-pick" type="button" class="btn btn-sm btn-primary">Choose image</button>
      <button id="heroImage-clear" type="button" class="btn btn-sm btn-ghost">Remove</button>
    </div>
  </div>
</div>

<script type="module">
  DotCustomFieldApi.ready(() => {
    const heroField = DotCustomFieldApi.getField('heroImage');

    const preview = document.getElementById('heroImage-preview');
    const placeholder = document.getElementById('heroImage-placeholder');
    const path = document.getElementById('heroImage-path');
    const pick = document.getElementById('heroImage-pick');
    const clear = document.getElementById('heroImage-clear');

    const render = (url) => {
      path.textContent = url || 'No image selected';
      preview.src = url || '';
      preview.classList.toggle('hidden', !url);
      placeholder.classList.toggle('hidden', !!url);
      clear.disabled = !url;
    };

    render(heroField.getValue() || '');

    pick.addEventListener('click', () => {
      DotCustomFieldApi.openBrowserModal({
        title: 'Select a hero image',
        kinds: ['file', 'dotasset'],
        mimeTypes: ['image/*'],
        onClose: (selection) => {
          if (!selection) return; // the editor cancelled

          // Files carry a path in `url`; dotAssets are served from /dA/{identifier}.
          const src = selection.kind === 'dotasset' ? '/dA/' + selection.identifier : selection.url;
          heroField.setValue(src);
          render(src);
        }
      });
    });

    clear.addEventListener('click', () => {
      heroField.setValue('');
      render('');
    });
  });
</script>

What the Code Does#

openBrowserModal() opens the same picker the Image and File fields use, with your own title and limited to images.

The asset picker titled Select a hero image, with a site selector and folder tree on the left and a list of images with status, locale and type on the right.

When the editor picks an image, onClose receives it; if they cancel, it receives null. For a file, use its url. For a dotAsset, the url doesn't point to the image, so build the address from its identifier with /dA/, as the example does. All the picker's options are listed in Custom Field Reference.