5

I have a custom context menu item added to /sitecore/content/Applications/Content Editor/Context Menues/Default.

I only want it to be displayed based on the item the context menu is being triggered on.

How do I modify the Command implementation to account for this logic?

Also is it possible to have it rules based instead of coding it into the Command Logic?

6

I would use the Rules Engine for this in a similar way to this answer I provided to restrict the publishing button.

string rulesFolder = "/sitecore/system/Settings/Rules/Menu Rules/Rules";

public override CommandState QueryState(CommandContext context)
{
    if (context.Items.Length != 1)
        return CommandState.Hidden;

    return RunRules(context);
}

private CommandState RunRules(CommandContext context)
{
    Item parentRuleItem;

    var ruleContext = new CommandRuleContext();
    ruleContext.Item = context.Items[0];

    using (new SecurityDisabler())
    {
        parentRuleItem = ruleContext.Item.Database.GetItem(rulesFolder);
        if (parentRuleItem == null)
            return CommandState.Hidden;
    }

    RuleList<CommandRuleContext> rules = RuleFactory.GetRules<CommandRuleContext>(parentRuleItem, "Rule");

    if (rules == null)
        return CommandState.Hidden;

    rules.Run(ruleContext);
    return ruleContext.CommandState;
}

You'll have to create the rulesFolder and populate it with the appropriate rules for your needs. The visibility of the menu options is now based on the defined rules and only visible if one of your rules match.

6

In your command class, you need to override the QueryState method. Here is how Sitecore PowerShell Extensions only shows its Edit with ISE context menu item on script items (source):

public override CommandState QueryState(CommandContext context)
{
    if (context.Items.Length != 1)
        return CommandState.Hidden;

    return context.Items[0].IsPowerShellScript()
        ? CommandState.Enabled
        : CommandState.Hidden;
}

If you wanted to invoke the rules engine from that method, you certainly could. Unfortunately, there does not seem to be a built-in way to use the rules engine for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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