How to call api within a Dashlet?

I am lost when it comes to API calls in SugarCRM..  I want to have a  better understanding.   

Can someone give me an example of dashlet with an API call  in it?

Thank you

Eventually I will need to create an api call that returns data for this query.

SELECT IFNULL(lev_contracts.id,'') primaryid
,IFNULL(lev_contracts.cost_center,'') cost_center
,IFNULL(assigned_user.id,'') assigned_user_id
,CONCAT(
IFNULL(assigned_user.first_name,''),
' ',
IFNULL(assigned_user.last_name,'')
) assigned_user_full_name
,lev_contracts.contract_id_gen contract_num
,IFNULL(lev_contracts.account_id_c,'') associated_account
,IFNULL(accounts1.name,'') associated_account_name
,IFNULL(lev_contracts.id,'') lev_contracts_id
,courses_cstm.lev_course_catalog_id_c course_catalog_id
,IFNULL(lev_course_catalog2.name,'') course_catalog_name
,IFNULL(courses.contact_id_c,'') courses_contact_id_c
,LTRIM(RTRIM( CONCAT(IFNULL(contacts3.first_name,''),' ',IFNULL(contacts3.last_name,'')) )) contacts3_name
,IFNULL(contacts3.id,'') contact3_id
,courses.start_date courses_start_date
,courses.billing_date courses_billing_date
,courses.total_client_fee courses_total_client_fee
,IFNULL( courses.currency_id,'') courses_TOTAL_CLIENT_FEE_CU4402B2
,courses.total_expense courses_total_expense
,IFNULL( courses.currency_id,'') courses_total_expense_currency
,courses.course_net courses_course_net
,IFNULL( courses.currency_id,'') courses_course_net_currency
,courses.gross_margin courses_gross_margin
FROM lev_contracts
LEFT JOIN lev_contracts_lev_courses_c contract_courses ON lev_contracts.id=contract_courses.lev_contracts_lev_courseslev_contracts_ida AND contract_courses.deleted=0

LEFT JOIN lev_courses courses ON courses.id=contract_courses.lev_contracts_lev_courseslev_courses_idb AND courses.deleted=0
INNER JOIN users assigned_user ON lev_contracts.assigned_user_id=assigned_user.id AND assigned_user.deleted=0

LEFT JOIN accounts accounts1 ON accounts1.id = lev_contracts.account_id_c
LEFT JOIN lev_courses_cstm courses_cstm ON courses.id = courses_cstm.id_c
LEFT JOIN lev_course_catalog lev_course_catalog2 ON lev_course_catalog2.id = courses_cstm.lev_course_catalog_id_c
LEFT JOIN contacts contacts3 ON contacts3.id = courses.contact_id_c

WHERE ({$this->where['billing_date']})
AND ({$this->where['cost_center']})
AND ({$this->where['associated_account']})
AND lev_contracts.deleted=0
ORDER BY lev_contracts.cost_center
, accounts1.name
,lev_contracts.contract_id_gen
,courses.billing_date ASC

  • Hi Amy,

    Please go through this link1 and link2  to get some idea about calling an external API in the dashlet. 

    Hope this information helps you. Slight smile

    Thanks!!

    Poojitha.K

  • Your dashlet has two parts:

    1) the API in custom/clients/base/api/.

    2) the View in custom/clients/base/views/.

    The view has three parts:

    1) the php metadata

    2) the javascript controller (this is where your API call will be to get the actual data)

    3) the hbs to display the data the way you want

    This is a basic example for a dashlet that displays some GDPR data from a non-Sugar database. The API gets the data.

    I created a directory:

    custom/clients/base/views/dashlet-GDPR

    in that directory define the metadata, note that my dashlet will be used in Contacts, Leads and Prospects in the record view.

    $viewdefs['base']['view']['dashlet-GDPR'] = array(
        'dashlets' => array(
            array(
                'label' => 'LBL_GDPR_LOOKUP_DASHLET',
                'description' => 'LBL_GDPR_LOOKUP_DASHLET_DESC',
                'config' => array(),
                'preview' => array(),
                'filter' => array(
                    'module' => array(
                        'Contacts',
                        'Leads',
                        'Prospects',
                    ),
                    'view' => 'record',
                ),
            ),
        ),
        'resources' => array(),
    );

    define your labels as app_strings in 

    custom/Extension/application/Ext/Language/.

    $app_strings['LBL_GDPR_LOOKUP_DASHLET'] = 'GDPR/Preferences Database Lookup (real time)';

    $app_strings['LBL_GDPR_LOOKUP_DASHLET_DESC'] = 'Displays customer preferences and GDPR from WBI maintainted databases searching by email address';


    in the controller the API retrieves the data and puts it in a varialble called resources, which you will see in the hbs

    ({
      tagName: 'ul',
      className: 'dashlet-GDPR',
      plugins: ['Dashlet','EmailClientLaunch'],
      resources: {},
      initDashlet: function(){
        var self = this,
            emails = self.model.get('email'),
            host = location.hostname;
        self.resources = new Object();
        _.each(emails, function(email){
          var address = encodeURIComponent(email.email_address),
              url = app.api.buildURL('getConsent/'+ address);
          app.api.call('GET', url, null, {
            success:function(data){
              _.each(data, function(value, key){
                if(data[key]['consent'] == false){
                  var icon = 'fa-ban',
                      color = 'red';
                }else if(data[key]['consent'] == true){
                  var icon = 'fa-check',
                      color = 'green';
                }
                var index = data[key]['email_address'] + data[key]['consent_key'];
                self.resources[index]={
                  'icon': icon,
                  'color': color,
                  'email_address': data[key]['email_address'],
                  'consent': data[key]['consent'],
                  'date': data[key]['updated'],
                  'consent_type': data[key]['consent_type']
                };
              });
              self.render();
            },
            error: function(e) {
              console.log(e);
            }
          });
        });
      },
      _dispose: function() {
        app.view.View.prototype._dispose.call(this);
      },
    })

    Note that the url = app.api.buildURL('getConsent/'+ address); is where the API call is defined. My custom API is called getConsent and given an email address it looks up consent. I am looping through the email addresses on the record to get consent for each one.

    The app.api.call is where the actual API call happens, it is a GET and the results of the API are read into the "data" variable.

    The API returns an array, in my case it looks something like this:

            $consent[] = array(
              'email_address' => $args['email_address'],
              'consent' => $pref['allow'],
              'consent_key' => "User Preferences: " . $key,
              'updated' => $pref['updated'],
              'consent_type' => "User Preferences: " . $key,
            );
            return($consent);

    The data is formatteed by the hbs in a table, I basically copied and edited a standard list view dashlet's hbs, note how it loops through the resources for each result

    {{!--

    */ formats output for GDPR dashlet

    --}}

    <div class="flex-list-view-content">

    <table class="table table-striped">

    <thead>

    <th> Consent Type </th>

    <th class='custom' width=10>Consent</th>

    <th>Email Address</th>

    <th>Consent Last Updated</th>

    </thead>

    <tbody>

    {{#each resources}}

    <tr>

      <td>{{consent_type}}</td>

      <td width=10px><span class="label label-module-sm {{color}}"><i class="fa {{icon}}" style="color:white"></i></span></td>

      <td data-type="email"><div class="ellipsis_inline" rel="tooltip" title data-placement="bottom" data-original-title="{{email_address}}"><a href="javascript:void(0);" data-action="email" data-email-to="{{email_address}}">{{email_address}}</a></td>

      <td data-type="date">{{date}}</td>

    </tr>

    {{/each}}

    </tbody>

    </table>

    </div>

     

    I hope this basic example helps. There are more complex ones around, and there are more details to get used to of course, like all the details in the dashlet metadata so it works in the modules and views you want etc... but hopefully this gets you started and you can find further details as needed.

    FrancescaS

  • Thank you for the examples.  I will study them.

    I need to know how to access data inside SugarCRM.

  • My example uses an API to get data from an external source but you can create an API to get data from Sugar.

    In your API you can use a SugarQuery or a Prepared Statement to get what you need.

  • I have created a  Hello World API, but the called the api is not return successfully or errors out.  That is it doesn't run the "success:" or "error:" scripts which include a console log.

    Thank you in advance.

    Any idea's what I am doing wrong?HelloWorldAPI.zip