Was this page helpful?

Setting default field values with a configurable UI Extension

Introduction

When working with UI Extensions it's a common task to make certain properties configurable. Examples are:

  • defining default values
  • project, category or entity identifiers when loading data from external APIs
  • Slack channel name to post messages to
  • which other content types to process (e.g. for publishing content trees)
  • what kind of validation to apply
  • and many more..

Such properties can be externalized from the source code of the UI Extension by defining configuration parameters and providing values for them. Later on configuration values are passed to the UI Extension through the UI Extensions SDK.

(The final UI Extension rendered in the entry editor. The default value of the field is the hex value for yellow which is #FFFF00)

(The appearance dialogue where the user can pick a default value for the color field.)

Preparation

Make sure you understand the concept of UI Extensions before reading this guide.

Types of configuration

There are two types of configuration that can be defined:

  • Installation parameters which are set on a space level. Values apply globally to every instance of an UI Extension within a space.
  • Instance parameters which are set when a UI Extension is assigned to a field of a content type. Values apply locally to an instance of a UI Extension.

Building the UI Extension

Step 1: Plan the configuration

For this exercise we will create a very simple UI Extension for short text fields which will assign a default value to every field the UI Extension is assigned to. The values are hex color values we want to pick from a predefined list.

The default options for our color are:

  • blue (#0000FF)
  • yellow (#FFFF00)
  • red (#FF0000)

Step 2: Define the UI Extension's meta data

Instance and installation parameters are defined when an extension is installed into a space. The easiest way to do that is by creating an extensions.json file and using the Contentful CLI to upload the UI Extension into a space.

{
  "id": "default-field-value",
  "name": "Default value for a field",
  "srcdoc": "extension.html",
  "fieldTypes": ["Symbol"],
  "parameters": {
    "instance": [
      {
        "id": "defaultColor",
        "name": "Default color",
        "description": "Set which color is the default color",
        "type": "Enum",
        "options": [{"#0000FF": "blue"}, {"#FFFF00": "yellow"}, {"#FF0000": "red"}],
        "labels": {"empty": "Choose a color"},
        "required": true
      }
    ]
  }
}

Under the parameters property we added an instance property which is used to define an enum type parameter with three pre-defined options for the colors.

For a full reference of parameter types and the values they support, please read about the configuration property of the extensions entity in the Content Management API.

Step 3: The code of the extension

We will define a very simple UI Extension for a Symbol field which means the field will hold a short text value of maximum 255 characters. To get going quickly, we were using the Vanilla HTML5 Template as a base. The final code looks like this:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://contentful.github.io/ui-extensions-sdk/cf-extension.css">
  <script src="https://unpkg.com/contentful-ui-extensions-sdk@3"></script>
</head>
<body>
  <div class="cf-form-field">
    <input type="text" class="cf-form-input">
    <div class="cf-form-hint">I am a UI Extension with a default value:
      <span class="default-value"></span>
    </div>
  </div>
  <script>
    'use strict';
    window.contentfulExtension.init(function (extension) {

      extension.window.startAutoResizer();

      var inputEl = document.querySelector('.cf-form-input');

      var detachValueChangeHandler = extension.field.onValueChanged(valueChangeHandler);

      inputEl.addEventListener('input', keyboardInputHandler);
      window.addEventListener('onbeforeunload', unloadHandler);

      var defaultColor = extension.parameters.instance.defaultColor;
      document.querySelector('.default-value').appendChild(document.createTextNode(defaultColor))

      if (extension.entry.getSys().version == 1 && extension.field.getValue() === undefined) {
        extension.field.setValue(defaultColor);
      }

      function valueChangeHandler(value) {
        inputEl.value = value;
        extension.field.setInvalid(isInvalidColor(value));
        document.querySelector(".cf-form-field").style.borderLeft = "5px solid " + value;
      }

      function keyboardInputHandler() {
        var value = inputEl.value;
        if (typeof value !== 'string' || value === '') {
          extension.field.removeValue();
        } else {
          extension.field.setValue(value);
        }
      }

      function isInvalidColor(value) {
        return value === undefined || value.match(/#([a-f0-9]{3}){1,2}\b/i) === null;
      }

      function unloadHandler() {
        window.removeEventListener('onbeforeunload', unloadHandler);
        inputEl.removeEventListener('input', keyboardInputHandler);
        detachValueChangeHandler();
      }
    });
  </script>
</body>
</html>

The basic logic we apply is:

Check if the version of the entry is 1 (so we are sure our default is only applied to new entries ):

extension.entry.getSys().version == 1

Check if the field the UI Extension is assigned to has an undefined value (so we are sure the field has not been populated during creation of the entry):

extension.field.getValue() === undefined

Then read the default value from configuration and assign it as the value of the field:

var defaultColor = extension.parameters.instance.defaultColor
extension.field.setValue(defaultColor);

You can find the final default-field-value UI Extension in our samples GitHub repository.

Summary

We covered:

  • configuration parameters for UI Extensions are great for encapsulation of configuration and re-usability of extensions
  • how configuration can be used to define default values for fields

Ressources