Dynamics 365 – Hide All Controls for an Attribute

In Dynamics 365, it’s not uncommon to have multiple controls associated with a single attribute on a form. This setup can be used for various purposes, such as displaying the same data in different sections. For instance, you might have a field like “Customer Name” displayed both as a text input for editing and as a label for viewing purposes. Managing these controls efficiently is crucial for maintaining a smooth user experience.

When working with forms, there may be instances where you need to dynamically show or hide these controls based on certain conditions. For example, you might want to hide specific fields for certain user roles or based on the values of other fields on the form. It’s relatively straightforward to show or hide a single control, but what if you have multiple controls for the same attribute? Let’s explore how to manage this scenario.

Example: Hiding a Single Control for an Attribute

Suppose you have a form where the “name” attribute is displayed as a text box. There may be scenarios where you need to hide this control based on certain conditions, such as the user role or the value of another field. Here’s how you can hide a single control for the “name” attribute:

// Access the form context (e.g., in an onLoad event)
var formContext = executionContext.getFormContext();

// Hide a single control for the "name" attribute
var attrControl= formContext.getControl(attrName);
if (attrControl) {
   attrControl.setVisible(false);
}

Example: Hiding All Controls for an Attribute

But what if an attribute has multiple controls on the form? You need to ensure that all these controls are hidden to completely remove the attribute from the user’s view. This can be particularly useful for fields that are conditionally required or irrelevant based on other data in the form. Here’s how to hide all controls associated with the “name” attribute:

// Access the form context (e.g., in an onLoad event)
var formContext = executionContext.getFormContext();

// Hide all controls for the "name" attribute
var attr = Xrm.Page.getAttribute(attrName);
attr.controls.forEach(function(control) {
     control.setVisible(false);
});

Leave a comment