Sonoma Partners Microsoft CRM and Salesforce Blog

Firing events in JavaScript when status changes in Dynamics CRM 2013/ 2015/ 2016

Today's post is written by Rob Montague, a Developer at Sonoma Partners.

I needed to show a specific section based on the status of the entity.  I was trying to use onload only, but unfortunately, this doesn’t trigger when the status changes even though the page pseudo-refreshes.

You can, however, add an on-change event to the statecode field and whenever the state changes, it will fire your event.

Sample Code:

function opportunityExecuteOnLoad() {
	hideShowSectionsBasedOnState();
    attachEvents();	
}

function attachEvents() {
	var statecode = Xrm.Page.getAttribute("statecode");
	if (statecode) {
	   statecode.addOnChange(hideShowSectionsBasedOnState);
	}	
}

function hideShowSectionsBasedOnState() {
    // Make Sure statecode exists and you can read value
    var stateCodeAttribute = Xrm.Page.getAttribute('statecode');
    if (!stateCodeAttribute || !stateCodeAttribute.getSelectedOption()) {
        return;
    }

    var stateCode = stateCodeAttribute.getSelectedOption(),
	// You can change "open" to whatever status you need
	isStatusOpen = stateCode.text.toLowerCase() === "open",
	generalTab = Xrm.Page.ui.tabs.get("general");

    // If general tab doesn’t exist, exit
    if (!generalTab) {
        return;
    }

    // Get the first section.  If it doesn’t exist, do nothing, otherwise 
    // If state is open, show it, otherwise hide it.
    var sectionToShowIfOpen = generalTab.sections.get("sectionToShowIfOpen");
    if (sectionToShowIfOpen) {
        sectionToShowIfOpen.setVisible(isStatusOpen);    
    }
    
    // Get the second section. If it doesn’t exist, do nothing, otherwise 
    // If the state is open, hide it, otherwise show it.
    var sectionToHideIfOpen = generalTab.sections.get("SectionToHideIfOpen");
    if (sectionToHideIfOpen) {
        sectionToHideIfOpen.setVisible(!isStatusOpen);    
    }
} 

You are now able to harness the status change event and customize your page whenever the state changes.

Topics: Microsoft Dynamics CRM 2013 Microsoft Dynamics CRM 2015 Microsoft Dynamics CRM 2016