Wednesday, October 13, 2021

SXA Custom Token - Best practices to include the operation correctly.

 When implementing SXA custom token, it would be good to consider the options like must, should or not, this is already part of the SXA model, so basically we need to make sure to include the below conditions.

Pass the model operation name as a parameter -


 public override void Process(ResolveSearchQueryTokensEventArgs args)

        {

            if (args.ContextItem == null)

                return;

            for (int index = 0; index < args.Models.Count; ++index)

            {

                SearchStringModel model = args.Models[index];

                if (model.Type.Equals("sxa") && this.ContainsToken(model))

                {

                    string str = model.Value.Replace(this.TokenPart, string.Empty).TrimStart('|');

                    var fieldNames = str.Split('|').ToList();

                    if (fieldNames.Any() && fieldNames.Count == 2)

                    {

                        args.Models.Insert(index, this.BuildModel(fieldNames[0], fieldNames[1], model.Operation));

                        args.Models.Remove(model);

                    }

                }

            }

        }


  protected virtual SearchStringModel BuildModel(

            string replace,

            string fieldValue, string operation)

        {

            return new SearchStringModel("custom", FormattableString.Invariant(FormattableStringFactory.Create("{0}|{1}", replace.ToLowerInvariant(), fieldValue)))

            {

                Operation = operation

            };

        }

Model operation values - Just for the reference.



No comments:

Post a Comment