Skip to content

Show or hide the 'Add New' button on form sub-grid based on the value on the form

Challenge:


How do I show or hide the 'Add New' button on form sub-grid based on the value on the form. 

You cannot use the ValueRule because the context of this rule must be run from a form Command Bar - so we must use a custom JavaScript rule.

Solution:

1. Create a JavaScript webresource that contains the function:

function ClientHooks_Ribbon_OpportunityRibbon_SubGridEnableRule() {
    var attribute = Xrm.Page.getAttribute('<your attribute logical name here>');
    return attribute.getValue() != null; // Return true to enable the button }

This function will be used to enable the sub-grid add button when there is a value in the attribute you reference.


2. Add the child entity that you want to change the sub-grid behaviour for to a solution. Also add the webresource with the javascript function above and then load the solution into the Ribbon Workbench.

2. Select the child entity from the Entities panel and identify which button you need to customise:]


3. Right-Click on the button and click Customize Command

4. The new command will show in the Solution Elements Panel and additionally all the referenced EnableRules and DisplayRules will also be added. Since we don’t need to customise these, we can select each one in turn and set IsCore=True in the properties panel.

5. Now to add the new ValueRule. Right click on the new customised command and click Edit Enable Rules.


6. Click Add New and then Add Step. Select Custom Javascript Rule and set the properties:

·         FunctionName = ClientHooks_Ribbon_OpportunityRibbon_SubGridEnableRule

·         Library = <Select the library you added above>

7. Click Publish

Refreshing the subgrid command bar

You will find that when the form is loaded, if there is a value in the attribute you have referenced in your enable rule, the Add New button will be visible. If however the value changes, the sub-grid command bar will not automatically refresh to reflect the new state. Upon adding or deleting rows in the sub-grid the command bar is refresh – but this isn’t much use in this case.

The main form command bar can be refreshed using Xrm.Page.ui.refreshRibbon() however this will not refresh sub-grid command bars. Instead, we can add an onchange event to the fields that are used in our VaueRule and call:

Xrm.Page.data.save();

This will refresh the sub-grids and re-evaluate any of the EnableRules however it will also save any other dirty attributes and so should be used with caution if you do not have auto-save enabled.

Feedback and Knowledge Base