Wednesday, June 29, 2011

Hide Tab Based on Picklist Value

CRM 2011: How to Hide a Tab Based on Picklist Value

Recently I ran into an issue with a piece of code I wrote for a new picklist field I added to an already existing entity to hide/show a tab depending on the value of the picklist. Here is a copy of the original code:
function ShowHideSection(PicklistFieldName, TabName)
{
    Xrm.Page.ui.tabs.get(TabName).setVisible(false);
    ////Check if Picklist value equals Yes, if so show the Tab
    if(Xrm.Page.getAttribute(PicklistFieldName).getSelectedOption().text == 'Yes') 
       {
       Xrm.Page.ui.tabs.get(TabName).setVisible(true);
       }
       else
       {
       Xrm.Page.ui.tabs.get(TabName).setVisible(false);
       }
}

While this code worked for all the new records I began creating, it did not work for the old records that existed before I created the new picklist field. When I created the new variable, I set its default value to No, but the records that existed before I added this new picklist were all set to unassigned (null). When I opened up an old record, I got the following error message:
There was an error with this field’s customized event.
Field: window
Event: onload
Error “Xrm.Page.getAttribute(…).getSelectedOption().text is null or not an object

Well this is a problem and something I did not account for!
I rewrote the code and declared the fields equal to a variable to handle checking for the unassigned value.
Here is the new code:
function ShowHideSection(PicklistFieldName, TabName)
{
     Xrm.Page.ui.tabs.get(TabName).setVisible(false);
    
var zPicklistField = Xrm.Page.data.entity.attributes.get(PicklistFieldName);
 
     if(zPicklistField.getValue() != null)
     {
         if(zPicklistField.getSelectedOption().text == 'Yes')
         {
         Xrm.Page.ui.tabs.get(TabName).setVisible(true);
         }
         else
         {
         Xrm.Page.ui.tabs.get(TabName).setVisible(false);
         }

     }
}
I hope this code can be of same use! Please let me know if you find a way to use it.

Thank you MDodd73 for your help.


2 comments:

  1. thanks a lot ! ! ! it's very usefull to check if an option set has been selected or not, indeed if it's null.
    :-)

    ReplyDelete
  2. Do i have Check the check box "pass context" when using in onchange of picklist field

    ReplyDelete