1

I'm working on a Sitecore 9.2 JSS project that needs a required field that results to FatalError. The default required field in Sitecore is using CriticalError.

I can create it manually in Sitecore but I'd like to do it in JSS so it can be used in the creation of templates and in other future JSS projects.

Is it possible? Has anyone did this already and would like to share?

2
  • When you say create field with validation, you mean in code first approach? Commented Jun 26, 2020 at 19:20
  • Your question is not clear, can you provide more details please. what do you mean by required field?, where and how you get those errors (FatalError, CriticalError)? can you show us how you create it manually and how you want it to be automate? Commented Jun 30, 2020 at 6:04

1 Answer 1

1

I assume that you are using the Code First Approach. In OOTB JSS, there are no attributes that allows you to specify the validation to use the Fatal Error. However, you can override the import process to have the field to use the fatal error.

Extend your manifest data

First, on the manifest definition, you need to add a new attribute. In my case, I named mine as IsFatalField.

export default manifest => {
  manifest.addComponent({
    name: "Welcome",
    fields: [
      { name: "title", type: manifest.fieldTypes.singleLineText, IsFatalField: "true" },
    ]
  });
};

Create a new Sitecore Validation Rule Item

As a best practice, instead of changing the current Required item available OOTB Sitecore, create a new validation at the path /sitecore/system/Settings/Validation Rules/Field Rules. In my case, I named mine as Fatal.

The validation is the same as the Required item except that in the Parameters field, I added Result=FatalError. See screenshot below

enter image description here

Override the ProcessTemplates pipeline

This processor is responsible to import the template to Sitecore based on your manifest. See below for code snippet.

public class ProcessTemplateWithValidation : ProcessTemplates
{
    protected override void ProcessField(TemplateItem template, Item multilistRoot, FieldDef fieldDef, ref int sortOrderIndex, IdManager idManager, AppConfiguration app)
    {
        ...
        //Remove code for brevity
        ...
        
        this.AssignRequiredValidation(field.InnerItem, fieldDef.Required, "Quick Action Bar");
        this.AssignRequiredValidation(field.InnerItem, fieldDef.Required, "Validate Button");
        this.AssignRequiredValidation(field.InnerItem, fieldDef.Required, "Validator Bar");
        this.AssignRequiredValidation(field.InnerItem, fieldDef.Required, "Workflow");
        
        //Customization to add Critical field validator
        var isFieldFatalString = fieldDef.AdditionalData?["IsFatalField"].ToString();

        if (!isFieldFatalString.IsNullOrEmpty())
        {
            var isFieldFatal = Convert.ToBoolean(isFieldFatalString);

            this.AssignCustomFieldValidation(field.InnerItem, isFieldFatal, "Quick Action Bar");
            this.AssignCustomFieldValidation(field.InnerItem, isFieldFatal, "Validate Button");
            this.AssignCustomFieldValidation(field.InnerItem, isFieldFatal, "Validator Bar");
            this.AssignCustomFieldValidation(field.InnerItem, isFieldFatal, "Workflow");
        }
    }

    protected virtual void AssignCustomFieldValidation(Item templateField, bool isFatal, string validationFieldName)
    {
        MultilistField field = templateField.Fields[validationFieldName];

        if (field == null)
        {
            Log.Warn("[JSS] - Could not find " + validationFieldName + " field on " + templateField.Paths.FullPath + "; validation settings may be incomplete.", (object)this);
        }
        else if (!isFatal)
        {
            field.Remove("{0E89EA60-AC6F-4619-8EDF-2057F307F19D}");
        }
        else
        {
            if (field.Contains("{0E89EA60-AC6F-4619-8EDF-2057F307F19D}"))
            {
                return;
            }

            field.Add("{0E89EA60-AC6F-4619-8EDF-2057F307F19D}");
        }
    }
}

In the overriden ProcessField method, the field definition AdditionalData property is read to retrieve the value of the IsFatalField. As the value is a string, it needs to be converted to a boolean and then passed to a new method (AssignCustomFieldValidation) I implemented.

Finally, you need a config file to patch the existing ProcessTemplates processor

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
  <sitecore role:require="ContentManagement or Standalone">
    <pipelines>
      <group groupName="javaScriptServices">
        <pipelines>
          <import>
            <processor 
              type="YourNamespace, YourAssemblyName"
              patch:instead="*[contains(@type, 'ProcessTemplates')]" />
          </import>
        </pipelines>
      </group>
    </pipelines>
  </sitecore>
</configuration>

Note

  • The full code is available at ProcessTemplateWithValidation.cs.

  • From Sitecore assembly reference, you can find it from the namespace Sitecore.JavaScriptServices.AppServices.Pipelines.Import.ProcessTemplates in the assembly Sitecore.JavaScriptServices.AppServices.

  • There are room for improvement for this implementation. I just added a basic example how you can achieve the validation. You may create a custom method that allows you to add any other validation you have.

More information is available at JSS - Extending the Import Pipeline.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.