Search code examples
javascriptdynamics-crmdynamics-crm-2016ribbon-button

How to disable ribbon button based on Form in Dynamics CRM 2016?


In this case I have two forms (Information & Manager) with ribbon Approve TOP. This button only enabled/view in Manager form.

I have followed this tutorial. I have already added javascript snippet that I set to my ribbon button enable rules. This is a sample of my code:

function EnableDisableRibbon_ApproveTop() {
    try {
        var formLabel;
        var currForm = Xrm.Page.ui.formSelector.getCurrentItem();
        formLabel = currForm.getLabel();
        
        if (formLabel == "Manager") {
            return true;
        }
        else {
            return false;
        }
    } catch (e) {
        alert("EnableDisableRibbon_ApproveTop : " + e.message);
    }
}

When I opened that form I got this error:

EnableDisableRibbon_ApproveTop : Cannot read property 'getCurrentItem' of null

EnableDisableRibbon_ApproveTop : Cannot read property 'getLabel' of null


Solution

  • 1.You have to add null check before trying to access child properties/methods like below:

    function EnableDisableRibbon_ApproveTop() {
        try {
            var formLabel;
            var selector = Xrm.Page.ui.formSelector;   
    
            if(selector != null){
                var currForm = selector.getCurrentItem();
    
                if(currForm != null){
                    formLabel = currForm.getLabel();
    
                    if (formLabel == "Manager") {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            }
        } catch (e) {
            alert("EnableDisableRibbon_ApproveTop : " + e.message);
        }
    }
    

    2.Make sure the user have access to both forms through security role, otherwise Xrm.Page.ui.formSelector returns null for single default form. read more

    3.Check the turbo form settings for legacy rendering, if it helps you to solve this error

    4.If the control is delayed loading - try setTimeout method to retry the snippet to call the EnableDisableRibbon_ApproveTop() method one more time

    Update:
    The blogpost you mentioned is another workaround, by setting the global formName variable from each form script instead of formSelector. This is done by overloaded set_formname() function inside Enablerule function RibbonButtonEnable.