March 26, 2013

Use and evaluate the Rule field type

In sitecore one of the field you can use is the "Rule" field. This field is very powerfull and you can easilly implmeent your own rules. Here is a very small tutorial on it.

First of all, on your template you should select the field of thype "Rule":

Now on your item you have an editor like this one:




And the following function return is a rule field is true:
public bool EvaluateRule(string fieldName, Item item) 
{
 var ruleContext = new RuleContext();
 foreach (Rule<RuleContext> rule in RuleFactory.GetRules<RuleContext>(new[] { item }, fieldName).Rules)
 {
     if (rule.Condition != null)
     {
  var stack = new RuleStack();
  rule.Condition.Evaluate(ruleContext, stack);

  if (ruleContext.IsAborted)
  {
      continue;
  }
  if ((stack.Count != 0) && ((bool)stack.Pop()))
  {
      return true;
  }
     }
 }
 
 return false;
}

6 comments:

  1. Hi Benjamin
    Ive just worked on a project where we are using the rules field in one of our templates. I just looked at the documentation, and it says

    "Warning
    Do not use the Rules field type in your data templates."

    Did you have any considerations on using the field type? or is it just working as expected?

    I would guess that Sitecore could change the way the field is functioning and maby breaking some functionality along the way.

    ReplyDelete
    Replies
    1. Could you tell me exactly where you have found this warning?

      Delete
  2. Hello,

    No it work as expected I din't had any troubles with it. But I will try to know why they have put it into they documentation and come back to you if I have an answer on it.

    Regards,

    ReplyDelete
  3. Hi Benjamin,
    thank you for your post however I am trying to manually evaluate rules/conditions from the code but I can get this working properly as my condition param is not getting populated. (i.e always null). I tried that as a conditional rendering and it worked perfectly fine. Not sure why it's happening.
    It would be really great if you can help me on this
    many thanks

    regards
    Ravi Silva

    ReplyDelete
    Replies
    1. Hello,

      Did you already:
      - Check into you web database if the field is present and have a value
      - check in the code if your item have a value with something like Sitecore.Context.Item["myField"] have a value
      - the same with Sitecore.Context.Item.Field["myField"] != null
      - Did you install DMS?

      Regards,

      Benjamin

      Delete
    2. Hi Benjamin,
      You're correct. For some reason the selected item in the condition wasn't publish
      All sorted now. Thank you very much for the help. means a lot :)

      Ravi

      Delete