Add custom business logic

Write a C# validation hook that refuses large discounts without an approval request, check it against the platform compiler and publish it.

Level
Intermediate
Estimated time
About 30 minutes
Uses
C# hooks, TAF Studio

What you will build

A validation hook on the Opportunity entity that runs before every insert and update.

Architecture

  1. Entity
  2. C# Hook
  3. Validation

Steps

  1. 1Create the script

    In Studio add a C# script bound to the Opportunity entity, with the Validate phase and the create and update operations. The class implements IValidationHook; the platform calls ValidateAsync by name.

  2. 2Write the rule

    Every message you add to context.Errors refuses the save and is shown to the user.

    DiscountRule.cs
    using TAF.Infra.QueryHook.Interfaces;
    using TAF.Infra.QueryHook.Models;
    
    public class DiscountRule : IValidationHook
    {
        public Task ValidateAsync(HookContext context)
        {
            if (context.Fields.TryGetValue("DiscountPercent", out var value)
                && Convert.ToDecimal(value) > 20
                && !context.Fields.ContainsKey("ApprovalRequest"))
            {
                context.Errors.Add("Discounts above 20% need an approval request.");
            }
            return Task.CompletedTask;
        }
    }
  3. 3Check it

    Run Check Script. Studio sends the code to the platform compiler and marks any errors in the editor. A validation hook that does not compile would block every save on the entity, so always check first.

  4. 4Publish and test

    Publish the script, then save an opportunity with a 25% discount. The save is refused with your message. Hooks are compiled on first use and cached.

Result

A server-side rule that applies to every screen, API call, workflow and TAFI change that writes an opportunity.

Screenshots

Step-by-step screenshots for this tutorial are coming soon.