๐ŸŽฏ What You'll Learn

In Model Driven Apps, there are scenarios where you need to programmatically disable all controls and fields within specific tab sections based on business logic, user roles, or data conditions. This tutorial will guide you through different approaches to achieve this functionality effectively.

Topics Covered:

  • Understanding tab and section structure in Model Driven Apps
  • Basic control disabling using forEach loops
  • Advanced error handling and validation
  • Performance optimization techniques
  • Real-world implementation scenarios

๐Ÿ“‹ Understanding Tab and Section Structure

Before diving into the code, it's essential to understand how Model Driven Apps organize forms into tabs, sections, and controls:

Structure

Form Hierarchy

  • Form Context: The main form object containing all elements
  • Tabs: Top-level containers that group related sections
  • Sections: Sub-containers within tabs that hold controls
  • Controls: Individual form elements (fields, lookups, etc.)

Each control in a Model Driven App form has properties and methods that allow you to manipulate its behavior, including the setDisabled() method we'll be using.

๐Ÿ”ง Basic Implementation

Let's start with the fundamental approach to disable all controls within a tab's sections:

Basic Control Disabling
javascript
// Basic implementation - disable all controls in a tab
function disableTabControls(executionContext, tabName) {
    // Get the form context
    const formContext = executionContext.getFormContext();
    
    // Get the specific tab
    const tab = formContext.ui.tabs.get(tabName);
    
    if (tab) {
        // Iterate through all sections in the tab
        tab.sections.forEach((section) => {
            section.controls.forEach((control) => {
                if (control && control.setDisabled) {
                    control.setDisabled(true);
                }
            });
        });
    }
}
๐Ÿ’ก

Pro Tip

Always check if the control and its setDisabled method exist before calling it to avoid runtime errors.

โšก Enhanced Implementation with Error Handling

For production environments, you need robust error handling and more flexibility:

Enhanced Control Management
javascript
/**
 * Enhanced function to manage control states in Model Driven Apps
 * @param {Object} executionContext - The execution context from the form event
 * @param {string} tabName - Name of the tab to target
 * @param {boolean} disabled - Whether to disable (true) or enable (false) controls
 * @param {Array} excludeControls - Array of control names to exclude from the operation
 */
function manageTabControlStates(executionContext, tabName, disabled = true, excludeControls = []) {
    try {
        // Validate input parameters
        if (!executionContext) {
            console.error('Execution context is required');
            return { success: false, error: 'Invalid execution context' };
        }

        if (!tabName) {
            console.error('Tab name is required');
            return { success: false, error: 'Tab name is required' };
        }

        // Get the form context
        const formContext = executionContext.getFormContext();
        
        if (!formContext) {
            console.error('Form context not available');
            return { success: false, error: 'Form context not available' };
        }

        // Get the specific tab
        const tab = formContext.ui.tabs.get(tabName);
        
        if (!tab) {
            console.warn(`Tab '${tabName}' not found`);
            return { success: false, error: `Tab '${tabName}' not found` };
        }

        let processedControls = 0;
        let errors = [];

        // Iterate through all sections in the tab
        tab.sections.forEach((section, sectionIndex) => {
            if (!section || !section.controls) {
                console.warn(`Section ${sectionIndex} has no controls`);
                return;
            }

            section.controls.forEach((control) => {
                try {
                    // Check if control exists and has the setDisabled method
                    if (!control || typeof control.setDisabled !== 'function') {
                        return;
                    }

                    // Get control name for exclusion check
                    const controlName = control.getName && control.getName();
                    
                    // Skip if control is in exclude list
                    if (excludeControls.includes(controlName)) {
                        console.log(`Skipping excluded control: ${controlName}`);
                        return;
                    }

                    // Apply the disabled state
                    control.setDisabled(disabled);
                    processedControls++;
                    
                    console.log(`Control '${controlName}' ${disabled ? 'disabled' : 'enabled'}`);
                    
                } catch (controlError) {
                    const errorMsg = `Error processing control: ${controlError.message}`;
                    console.error(errorMsg);
                    errors.push(errorMsg);
                }
            });
        });

        const result = {
            success: true,
            processedControls,
            tabName,
            action: disabled ? 'disabled' : 'enabled',
            errors: errors.length > 0 ? errors : null
        };

        console.log(`Successfully ${disabled ? 'disabled' : 'enabled'} ${processedControls} controls in tab '${tabName}'`);
        return result;

    } catch (error) {
        const errorMsg = `Error in manageTabControlStates: ${error.message}`;
        console.error(errorMsg);
        return { success: false, error: errorMsg };
    }
}

๐Ÿ“– Usage Examples

Here are practical examples of how to use the function in different scenarios:

Example 1

Disable All Controls in a Tab

Form OnLoad Event
javascript
// Call from Form OnLoad event
function onFormLoad(executionContext) {
    // Disable all controls in the "Details" tab
    const result = manageTabControlStates(executionContext, "Details", true);
    
    if (!result.success) {
        console.error("Failed to disable controls:", result.error);
    }
}
Example 2

Conditional Control Management

Field OnChange Event
javascript
// Call from a field's OnChange event
function onStatusChange(executionContext) {
    const formContext = executionContext.getFormContext();
    const statusValue = formContext.getAttribute("statuscode").getValue();
    
    // Disable "Additional Information" tab if status is "Completed"
    if (statusValue === 100000001) { // Completed status
        manageTabControlStates(
            executionContext, 
            "AdditionalInfo", 
            true, 
            ["createdon", "modifiedon"] // Exclude system fields
        );
    } else {
        // Enable controls if status is not completed
        manageTabControlStates(executionContext, "AdditionalInfo", false);
    }
}
Example 3

Role-Based Control Management

User Role Check
javascript
// Role-based control management
function applyRoleBasedSecurity(executionContext) {
    const userSettings = Xrm.Utility.getGlobalContext().userSettings;
    const userRoles = userSettings.roles;
    
    // Define role GUIDs (replace with your actual role GUIDs)
    const ADMIN_ROLE_ID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    const MANAGER_ROLE_ID = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy";
    
    // Check if user has admin or manager role
    const hasAdminAccess = userRoles.some(role => 
        role.id === ADMIN_ROLE_ID || role.id === MANAGER_ROLE_ID
    );
    
    if (!hasAdminAccess) {
        // Disable sensitive tabs for non-admin users
        manageTabControlStates(executionContext, "FinancialInfo", true);
        manageTabControlStates(executionContext, "AdminSettings", true);
    }
}

๐Ÿš€ Performance Optimization

For forms with many controls, consider these optimization techniques:

Optimized Batch Processing
javascript
/**
 * Optimized function for processing large forms
 */
function optimizedControlManagement(executionContext, tabName, disabled = true) {
    return new Promise((resolve, reject) => {
        try {
            const formContext = executionContext.getFormContext();
            const tab = formContext.ui.tabs.get(tabName);
            
            if (!tab) {
                reject(new Error(`Tab '${tabName}' not found`));
                return;
            }

            // Collect all controls first
            const allControls = [];
            tab.sections.forEach(section => {
                if (section && section.controls) {
                    section.controls.forEach(control => {
                        if (control && typeof control.setDisabled === 'function') {
                            allControls.push(control);
                        }
                    });
                }
            });

            // Process controls in batches to avoid blocking UI
            const batchSize = 10;
            let currentIndex = 0;

            function processBatch() {
                const endIndex = Math.min(currentIndex + batchSize, allControls.length);
                
                for (let i = currentIndex; i < endIndex; i++) {
                    allControls[i].setDisabled(disabled);
                }
                
                currentIndex = endIndex;
                
                if (currentIndex < allControls.length) {
                    // Schedule next batch
                    setTimeout(processBatch, 0);
                } else {
                    // All controls processed
                    resolve({
                        success: true,
                        processedControls: allControls.length,
                        tabName
                    });
                }
            }

            // Start processing
            processBatch();

        } catch (error) {
            reject(error);
        }
    });
}

// Usage with async/await
async function handleLargeForm(executionContext) {
    try {
        const result = await optimizedControlManagement(executionContext, "LargeTab", true);
        console.log(`Processed ${result.processedControls} controls successfully`);
    } catch (error) {
        console.error("Error processing form:", error.message);
    }
}
โ„น๏ธ

Performance Tips

  • Process controls in batches for large forms
  • Cache form context references when possible
  • Use setTimeout(0) to yield control back to the browser
  • Consider using web workers for very heavy operations

โœ… Best Practices

๐ŸŽฏ Key Best Practices

๐Ÿ›ก๏ธ

Error Handling

Always validate existence of controls and methods before calling them to prevent runtime errors.

๐Ÿ“

Logging

Implement comprehensive logging to track what controls are being modified for debugging purposes.

โšก

Performance

For forms with many controls, use batch processing to avoid blocking the user interface.

๐Ÿ”„

Reversibility

Always provide a way to enable controls back when business logic conditions change.

๐ŸŽฏ

Selective Targeting

Use exclusion lists to skip system fields or critical controls that should remain functional.

๐Ÿงช

Testing

Test thoroughly across different user roles, browsers, and form configurations.

โš ๏ธ Common Issues and Solutions

Issue 1

Control Not Found Error

Problem: JavaScript error when trying to access controls that don't exist.

Solution: Always check if the control exists before calling methods:

if (control && typeof control.setDisabled === 'function') {
    control.setDisabled(true);
}
Issue 2

Tab Not Loading Properly

Problem: Tab sections are not accessible immediately on form load.

Solution: Use setTimeout or form ready events:

setTimeout(() => {
    manageTabControlStates(executionContext, "TabName", true);
}, 100);
Issue 3

Performance Issues on Large Forms

Problem: Browser becomes unresponsive when processing many controls.

Solution: Use the optimized batch processing approach shown earlier in this article.

๐ŸŽ‰ Conclusion

Programmatically managing control states in Model Driven Apps is a powerful technique for implementing dynamic forms based on business logic. The key to success is:

โœ…

Summary

  • Start with the basic tab.sections.forEach() approach
  • Enhance with proper error handling and validation
  • Optimize for performance when dealing with large forms
  • Test thoroughly across different scenarios and user roles
  • Always provide ways to reverse the changes when needed

This approach gives you fine-grained control over your Model Driven App forms, enabling you to create sophisticated, user-friendly applications that adapt to your business requirements.