Dynamically Hiding Subpanels Based on Record Values
Overview
This article will demonstrate how to dynamically hide subpanels that are dependent on record values by overriding the subpanels
layout for a module. This example is for an account record where we will hide the Contacts subpanel when the account type is not 'Customer'.
Example
To accomplish this, we will create a JavaScript controller that extends SubpanelsLayout
. This controller will then monitor the model and control the display of the subpanels.
./custom/modules/Accounts/clients/base/layouts/subpanels/subpanels.js
Removed script tag to: https://gist.github.com/3722771.js?file=view.detail.php
({
extendsFrom: 'SubpanelsLayout',
_hiddenSubpanels: [],
initialize: function(options) {
this._super('initialize', [options]);
this.registerModelEvents();
},
/**
* Add the model change events for fields that determine when a subpanel should be hidden
*/
registerModelEvents: function(){
this.model.on('change:account_type',function(model) {
var link = 'contacts';
if (model.get('account_type') == "Customer"){
this.unhideSubpanel(link);
}else{
this.hideSubpanel(link);
}
},this);
},
/**
* Override showSubpanel to re-hide subpanels when outside changes occur, like reordering subpanel
* @inheritdoc
*/
showSubpanel: function(linkName) {
this._super('showSubpanel',[linkName]);
_.each(this._hiddenSubpanels, function(link) {
this.hideSubpanel(link);
},this);
},
/**
* Helper for getting the Subpanel View for a specific link
*/
getSubpanelByLink: function(link){
return this._components.find(function(component){
return component.context.get('link') === link;
});
},
/**
* Add to the _hiddenSubpanels array, and hide the subpanel
*/
hideSubpanel: function(link){
this._hiddenSubpanels.push(link);
var component = this.getSubpanelByLink(link);
if (!_.isUndefined(component)){
component.hide();
}
this._hiddenSubpanels = _.unique(this._hiddenSubpanels);
},
/**
* Unhide the Subpanel and remove from _hiddenSubpanels array
*/
unhideSubpanel: function(link){
var index = this._hiddenSubpanels.findIndex(function(l){
return l == link;
});
if (_.isUndefined(index)){
delete this._hiddenSubpanels[index];
}
var component = this.getSubpanelByLink(link);
if (!_.isUndefined(component)){
component.show();
}
}
})
Once the file is in place, run a Quick Repair and Rebuild. The changes will then be reflected in the Accounts record view.