SugarCRM — Conditional Actions

Posted on Thu 15 October 2015 in Tech

Say you need to hide certain actions in Sugar depending on the status of a field, I've come across a great snippet of code from an awesome comment by Felix Nilam on the SugarCRM forums and wanted to show you a brief snippet of how it could work.

Make sure to call it before render, otherwise I had issues with this.meta.buttons already having rendered.

({
    extendsFrom: 'RecordView',

initialize: function (options) {
        app.view.invokeParent(this, {type: 'view', name: 'record', method: 'initialize', args:[options]});
        this.before('render', this.mycustom_button_visibility, this);
        this.before('render', this.mycustom2_button_visibility, this);
    },
    mycustom_button_visibility : function() {
        if(typeof this.model.get('some_field') != 'undefined'
        && this.model.get('some_field') != 'some_value') {
            this.hide_button('some_button_name');
        }
    },
    mycustom2_button_visibility : function() {
        if(typeof this.model.get('some_second_field') != 'undefined'
        && this.model.get('some_second_field') != 'some_value') {
            this.hide_button('some_second_button_name');
        }
    },
    hide_button: function(name) {
        var button_sel = '';
        var button_index = '';
        // find the buttons index for the share button
        _.find(this.meta.buttons, function(bn, idx) {
            if(bn.name == 'main_dropdown') {
                button_sel = idx;
                _.find(bn.buttons, function(bbn, idx_bbn) {
                    if(bbn.name == name) {
                        button_index = idx_bbn;
                        return true;
                    }
                });
                return true;
            }
        });
        if(button_sel != '' && button_index != '')
        {
            //remove the meta
            this.meta.buttons[button_sel].buttons.splice(button_index, 1);
        }
    }
})

Props to Felix for the snippet and I hope this helps others.