Newer Version Available

This content describes an older version of this product. View Latest

tpmGenericUtils Module Reference

This component provides replacements for accessing @salesforce modules on components with runtimeNamespace cgcloud defined.

The content in this Consumer Goods Cloud Trade Promotion Management documentation is confidential and may be viewed only by customers or partners as authorized by Salesforce, and copying and further distribution is prohibited without prior written consent from Salesforce. The content is the highly confidential and proprietary information of Salesforce and is protected under the confidentiality obligations of your Agreement with Salesforce. Accordingly, the content may be used only as necessary in order to implement the Consumer Goods Cloud Trade Promotion Management functionality.

The content in this documentation is being released as a preview, and is not generally available and may contain errors. Salesforce is providing this documentation as-is, and makes no representations or warranties as to the accuracy of the content contained in this documentation. Salesforce reserves the right to update and revise this documentation, and content describing features of Consumer Goods Cloud Trade Promotion Management may be modified, added, or removed. If Salesforce distributes or releases updated versions of this documentation, you acknowledge and agree that you will delete and destroy any prior versions of this documentation.

Important

Namespace

1cgcloud

Implementation Example

1import {
2  apex,
3  apexCacheable,
4  getResponse,
5  getStaticResourceURL,
6  i18n,
7  UserId,
8  refreshApex,
9  getSObjectValue,
10  FORM_FACTOR,
11  CGCloudNamespace,
12  CGCloudNamespaceWithUnderscore
13} from 'cgcloud/tpmGenericUtils';

Performing APEX Calls

To call apex methods, this module provides the apex and apexCacheable functions that can be used for that purpose. First, lets define the APEX method to be called. The APEX method to be called needs to be a global class implementing the System.Callable interface.

1global with sharing class ApexTest implements System.Callable {
2  global class ApexTestException extends Exception {}
3
4  // Interface method
5  public Object call(String method, Map<String, Object> params) {
6    // Both method and params will be received
7    if (method == 'getAccounts') {
8        return getAccounts(params);
9    } else {
10        // Exceptions can be thrown
11        throw new Exception('Invalid method!');
12    }
13  }
14  
15  private static List<Account> getAccounts(Map<String, Object> params) {
16    // Validate parameters
17    if (params == null || String.isBlank((String) params.get('searchKey')) == null) {
18        return new List<Account>();
19    }
20    
21    // Extract parameters.
22    // NOTE: Javascript Dates are received as Strings, they need to be parsed 
23    // with
24    // Date newDate = Date.valueOf((String.valueOf(dateString)));
25    String searchKey = String.valueOf(params.get('searchKey'));
26    String searchKeyProcessed = '%' + String.escapeSingleQuotes(searchKey) + '%';
27    
28    // return
29    return [SELECT Id, Name FROM Account WHERE Name LIKE :searchKeyProcessed LIMIT 100];
30  }
31}

In your custom LWC, you can use the apex and “apexCacheable” methods to call for this function. The difference between apex and apexCacheable is that apexCacheable will use the Lightning Web Components caching layer.

1import { api, wire, LightningElement } from 'lwc';
2
3import {
4  CGCloudNamespaceWithUnderscore,
5  apexCacheable,
6  apex,
7  getResponse,
8  refreshApex
9} from 'cgcloud/tpmGenericUtils';
10
11export default class MyApexTestComponent extends LightningElement {
12    
13    imperativeData = null;
14    
15    wiredResponse = null;
16    wiredData = null;
17    
18    // Store the params for the request
19    requestParams = {
20        searchKey = ''
21    };
22    
23    // It's possible to use the wire adapter only with the apexCacheable method
24    @wire(apexCacheable, {
25      descriptor: {
26        className: 'ApexTest',
27        method: 'getAccounts'
28      },
29        params: '$requestParams'
30    })
31    wiredFunction(value) {
32      this.wiredResponse = value; // Save wired data to be able to call
33                                    // refreshApex later
34      const { data, error } = getResponse(value); // Use 'getResponse' to extract data
35      if (error) {
36        console.error(error);
37      }
38      this.wiredData = data;
39    }
40    
41    onSearchKeyChange(event) {
42        // Set the new parameters
43        this.requestParams = {
44            searchKey = event.detail.value
45        };
46        // The change to requestParams will trigger a refresh of 
47        // the wire adapter data.
48    }
49    
50    onOtherEvent() {
51        // You can force-refresh the wire adapter data
52        // with refreshApex
53        refreshApex(this.wiredResponse);
54    }
55    
56    // You can call APEX method imperatively
57    imperativeApex() {
58        apex({ // You can also use apexCacheable to cache the response
59          descriptor: {
60            className: 'ApexTest',
61            method: 'getAccounts'
62          },
63          params: this.requestParams
64        })
65        .then(getResponse) // use getResponse to extract data
66        .then((data) => {
67            this.imperativeData = data;
68        });
69    }
70}

Loading Static Resources

In order to load static resources, you can use the getStaticResourceURL function to get the Static resource URL and load it using standard Lightning Web Components tools.

1import { LightningElement } from 'lwc';
2import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
3import {
4  getStaticResourceURL
5} from 'cgcloud/tpmGenericUtils';
6
7// getStaticResourceURL returns a Promise
8const myZippedResourceURLPromise = getStaticResourceURL('MyZippedResource');
9
10export default class MyStaticResourceComponent extends LightningElement {
11
12    connectedCallback() {
13        // Wait for the Base URL promise to resolve
14        myZippedResourceURLPromise
15            .then((baseURL) => Promise.all([
16                // load your resources
17                loadScript(this, baseURL + '/MyScript.js'),
18                loadStyle(this, baseURL + '/MyStyle.css')
19            ]))
20            .then(() => {
21                // You can use your resource after loaded
22                window.MyApp.run();
23            });
24    }
25}

Access Internationalization Properties

You can use the i18n object to get Internationalization properties. The properties exposed are the ones described in Salesforce Developer Component Library Documentation

1import {
2  i18n
3} from 'cgcloud/tpmGenericUtils';
4
5console.log(i18n);
6
7// {
8//   "lang": "en-US",
9//   "dir": "ltr",
10//   "locale": "en-US",
11//   "currency": "USD",
12//   "firstDayOfWeek": 1,
13//   "datetime": {
14//     "shortDateFormat": "M/d/yyyy",
15//     "mediumDateFormat": "MMM d, yyyy",
16//     "longDateFormat": "MMMM d, yyyy",
17//     "shortDateTimeFormat": "M/d/yyyy, h:mm a",
18//     "mediumDateTimeFormat": "MMM d, yyyy, h:mm:ss a",
19//     "shortTimeFormat": "h:mm a"
20//   },
21//   "number": {
22//     "currencyFormat": "¤#,##0.00",
23//     "currencySymbol": "$",
24//     "decimalSeparator": ".",
25//     "groupingSeparator": ",",
26//     "numberFormat": "#,##0.###",
27//     "percentFormat": "#,##0%"
28//   },
29//   "timeZone": "America/Los_Angeles"
30// }

Get current user Id

The current User id is returned by the UserId attribute

1import {
2  UserId
3} from 'cgcloud/tpmGenericUtils';
4
5console.log(UserId);
6
7// 005TC0000002jXJYAY

Get client Form Factor

The client form factor is returnd by the FORM_FACTOR attribute

1import {
2  FORM_FACTOR
3} from 'cgcloud/tpmGenericUtils';
4
5console.log(FORM_FACTOR);
6
7// Large

Get CGCloud Namespace

You can get the CGCloud Namespace with the Properties CGCloudNamespace andCGCloudNamespaceWithUnderscore.

1import {
2  CGCloudNamespace,
3  CGCloudNamespaceWithUnderscore
4} from 'cgcloud/tpmGenericUtils';
5
6console.log(CGCloudNamespace);
7
8// cgcloud
9
10console.log(CGCloudNamespaceWithUnderscore);
11
12// cgcloud__