Pages

Monday, August 10, 2015

SugarCRM Quick Hit: SugarBean and JavaScript

Sometimes in the course of customization work we may be performing within Sugar we may have a need to load one or more records from a module. 

For example, we may need to load an entry from the Calls module. Or, as demonstrated in a recent example I posted, we may need a set of records from the Leads module.

The Sidecar framework in Sugar 7 makes this process quite easy via the app.data namespace. Here are a few examples that should help.

To load a single record from a given module:

var myRecord = app.data.createBean('Leads', {id:<record_id>});
myRecord.fetch();

Loading multiple records from a given module:

var myRecords = app.data.createBeanCollection('Leads');
myRecords.fetch();

Note the use of the fetch() method in both examples. It is used to actually instruct Backbone to execute the necessary calls to request the desired data via the Sugar REST v10 API. 

In the case of the first example, the JSON object passed as the second parameter ({id:<record_id>}) allows us to specify the ID of the record we wish to retrieve. However, in the second example, you will notice we are not specifying a similar property. 

When executed, the second example retrieves the first page of the same set of records that would otherwise be displayed to the current user should the user instead access the ListView for the same module. By default, that would be the first 20 records accessible to the current user, ordered by date_modified, descending.

But what if we wanted greater control over which records or fields are retrieved? That brings us back to the fetch() method mentioned earlier.

The fetch() method allows us to specify a number of additional parameters, including: filter, fields, success and others.

Here is an example of where the fields and filter parameters are defined and used to retrieve only the id and status fields for those leads created within the current month.

var leads = app.data.createBeanCollection('Leads');
leads.fetch({
        fields: ['id', 'status'],
        filter:[{'date_entered':{'$dateRange':'this_month'}}],
    });

Hope that helps!