Adding A Prevalue Source Type To Umbraco Forms

This builds on the "Adding a type to the provider model" article

Add a new class to your project - inherit it from Umbraco.Forms.Core.FieldPreValueSourceType and implement the class.

The following example shows an illustrative custom prevalue source type that returns a hard-coded list of values. It can be extended for your needs via injection of services via the constructor. (See additional example at the bottom.)

Dynamic settings can be applied and validated as shown in the Validate type settings with ValidateSettings() article.

using System;
using System.Collections.Generic;
using Umbraco.Forms.Core;
using Umbraco.Forms.Core.Models;

namespace MyFormsExtensions
{
    public class FixedListPrevalueSource : FieldPreValueSourceType
    {
        public FixedListPrevalueSource()
        {
            Id = new Guid("42C8158D-2AA8-4621-B653-6A63C7545768");
            Name = "Fixed List";
            Description = "Example prevalue source providing a fixed list of values.";
        }

        public override List<PreValue> GetPreValues(Field field, Form form) =>
            new List<PreValue>
            {
                new PreValue
                {
                    Id = 1,
                    Value = "item-one",
                    Caption = "Item One"
                },
                new PreValue
                {
                    Id = 2,
                    Value = "item-two",
                    Caption = "Item Two"
                }
            };

        /// <inheritdoc/>
        public override List<Exception> ValidateSettings()
        {
        // this is used to validate any dynamic settings you might apply to the PreValueSource
        // if there are no dynamic settings, return an empty list of Exceptions:
            var exceptions = new List<Exception>();
            return exceptions;
        }
    }
}

You will then need to register this new prevalue source type as a dependency.

The PreValue model in Umbraco Forms Versions 8.13.0, 9.5.0, 10.1.0, and above includes a .Caption property. This property is set separately from the .Value property. In the previous versions, the Value is generally used as the caption when rendered on the form.

Another Example Using Dependency Injection to Access Additional Services

This example will take a user-provided Content Node and create a custom Prevalue list from the property data on that node. Your own FieldPreValueSourceType can get its data from wherever you like - an API call, custom functions, etc.

You will then need to register this new type as a dependency (either in Program.cs or in your own IComposer, as shown here).

Last updated

Was this helpful?