Loading
Connect in real time with the Trailblazer Community in Slack Open BetaRead More
Set Up Trade Promotion Management
Sample Custom Wrapper for the TPM Trade Planning Component

Sample Custom Wrapper for the TPM Trade Planning Component

Start a custom implementation from a sample wrapper that adds a toolbar button, handles events, and calls @api methods on the TPM Trade Planning LWC.

Required Editions

Available in: Lightning Experience
Available in: Enterprise, Unlimited, Einstein 1, and Agentforce 1 Editions with Consumer Goods Cloud Trade Promotion Management

The sample wrapper component, myCustomTradePlanning, shows how to customize the TPM Trade Planning Lightning web component (cgcloud-tpm-trade-planning) from a custom wrapper. The wrapper adds a Promotions button to the toolbar, lists the promotions loaded in the Trade Calendar in a panel, and responds to view and status changes. Use the sample wrapper as a starting point, and replace its placeholder handlers with your own logic.

How the Sample Wrapper Customizes the Page

The sample wrapper combines four customization options of the TPM Trade Planning LWC.

  • Toolbar slot—A lightning-button in the center-buttons slot adds a Promotions button to the toolbar without replacing any existing buttons. The button label shows the current promotion count. For the other toolbar and header slots, see Slots for Custom Toolbar and Header Content.
  • Event handlers—Template handlers bind to promotionlistchange, viewchange, and statuschange directly on cgcloud-tpm-trade-planning. The TPM Trade Planning LWC dispatches the state events of the business objects (BOs) again on itself, so the wrapper doesn't need renderedCallback() wiring. Only the Trade Calendar dispatches promotionlistchange, so the Promotions panel isn't updated in Account Plan. After a user switches from the Trade Calendar to Account Plan on the same page, statuschange doesn't report Account Plan status changes. For the full event list, see Events for Listening to Page State.
  • Promotions panel—The onPromotionList() handler maps event.detail.value to a list with each promotion's name, calendar group, phase, and formatted date range. In each entry of event.detail.value, name holds the promotion slogan, template holds the name of the calendar row (group) that contains the promotion, and status holds the promotion phase. The handler stores these values as name, group, and phase.
  • Imperative methods—The getApi() accessor returns cgcloud-tpm-trade-planning by its data-id. The wrapper calls @api methods such as setEARight(), getProperty(), refresh(), and runViewAction() on that component only. For the action methods, see Programmatic Actions for Triggering Toolbar Buttons from Code.

The enforceErrorMode() method shows how to change button access rights from code. When isError is true, the method calls setEARight('TP_REFRESH', { editable: false }), which keeps the Refresh button visible but makes it unavailable. For all access-rights codes, see Edit and Access Rights for Toolbar Buttons.

Important
Important Call methods and attach listeners only on cgcloud-tpm-trade-planning. Don't reference the private inner BO components from your wrapper. The inner components aren't exposed (isExposed=false), so a reference to them fails to compile in a subscriber org.
Note
Note Mass Copy (the Copy Promotions button) requires the Aura wrapper. When the TPM Trade Planning Aura wrapper (TradePlanningComponent) hosts the LWC, it passes the LWC a reference that the LWC uses to create the Aura components that run Mass Copy. A custom LWC wrapper placed directly on a Lightning page can't pass this reference. Without it, Mass Copy shows its in-progress message but doesn't copy any promotions. If your users need Mass Copy, use the Aura wrapper (TradePlanningComponent).

When you embed the LWC in a custom component, you can set the attributes. For TPM Trade Planning LWC attributes, see TPM Trade Planning LWC Attributes.

Sample Wrapper Files and Metadata

The sample wrapper is a standard LWC bundle with three files.

  • myCustomTradePlanning.html—The template that hosts cgcloud-tpm-trade-planning, the Promotions button, and the promotions panel.
  • myCustomTradePlanning.js—The class that holds the promotion list, the event handlers, the getApi() accessor, and the date formatter.
  • myCustomTradePlanning.js-meta.xml—The metadata file that exposes the wrapper in Lightning App Builder.

The metadata file sets isExposed to true and declares the lightning__AppPage target, so the wrapper appears in Lightning App Builder as My Custom Trade Planning for app pages. The sample uses API version 66.0. To place the wrapper on other page types, add their targets to the <targets> element.

The onView() and onStatus() handlers are empty placeholders. For example, in onStatus(), show a toast when the status is 'ERROR', or call enforceErrorMode() to make the Refresh button unavailable while the error lasts.

Sample Wrapper Code
Sample Wrapper Code

This HTML template, myCustomTradePlanning.html, binds three event handlers on cgcloud-tpm-trade-planning, adds a Promotions button to the center-buttons slot, and shows the promotions panel when showPanel is true.

<template>
 <cgcloud-tpm-trade-planning
  data-id="tradePlanning"
  product-fields={productFields}
  onpromotionlistchange={onPromotionList}
  onviewchange={onView}
  onstatuschange={onStatus}>
    <!-- inject a button into the toolbar -->
    <lightning-button
      slot="center-buttons"
      label={btnLabel}
      icon-name="utility:list"
      variant="brand-outline"
      onclick={onPromosClick}>
    </lightning-button>
  </cgcloud-tpm-trade-planning>

  <template lwc:if={showPanel}>
    <section class="slds-card">
      <header class="slds-card__header">
        <h2 class="slds-card__header-title">Promotions ({promotionCount})</h2>
      </header>
      <ul>
        <template for:each={promotions} for:item="p">
          <li key={p.id}>
            <strong>{p.name}</strong> — {p.group} ({p.phase})
            <br /><small>{p.dateRange}</small>
          </li>
        </template>
      </ul>
    </section>
  </template>
</template>

This JavaScript class, myCustomTradePlanning.js, stores the promotion list, formats each promotion's date range, shows or hides the panel, and calls setEARight() through getApi().

import { LightningElement, api, track } from 'lwc';

export default class MyCustomTradePlanning extends LightningElement {
  @api productFields;
  @track promotions = [];
  showPanel = false;

  get promotionCount() {
    return this.promotions.length;
  }
  get btnLabel() {
    return `Promotions (${this.promotionCount})`;
  }

  // All BO state events are re-dispatched on <cgcloud-tpm-trade-planning>, so we
  // bind them via template handlers (above) — no renderedCallback wiring
  // needed. If you need to call methods (setEARight, getProperty, refresh,
  // runViewAction …), get <cgcloud-tpm-trade-planning> via getApi() and call the
  // @api method on it. Never reach into the private inner BO LWCs.
  getApi() {
    return this.template.querySelector('[data-id="tradePlanning"]');
  }

  onPromotionList(event) {
    const list = event.detail.value || [];
    this.promotions = list.map((p) => ({
      id: p.id,
      name: p.name || 'Untitled',
      group: p.template || '',   // calendar row (group) name, not the promotion template
      phase: p.status || '',     // promotion phase label
      dateRange: this._fmt(p.startDate, p.endDate)
    }));
  }

  onView(event) {
    /* respond to view change */
  }
  onStatus(event) {
    /* respond to status change (e.g. show toast on ERROR) */
  }

  onPromosClick() {
    this.showPanel = !this.showPanel;
  }

  // Programmatic example: disable Refresh when an error appears.
  // setEARight is an @api method on <cgcloud-tpm-trade-planning> — call it via getApi().
  enforceErrorMode(isError) {
    this.getApi()?.setEARight('TP_REFRESH', { editable: !isError });
  }

  _fmt(start, end) {
    if (!start && !end) return '';
    const opts = { month: 'short', day: 'numeric' };
    const s = start ? new Date(start).toLocaleDateString(undefined, opts) : '?';
    const e = end ? new Date(end).toLocaleDateString(undefined, opts) : '?';
    return `${s} – ${e}`;
  }
}

This metadata file, myCustomTradePlanning.js-meta.xml, exposes the wrapper on Lightning app pages.

<?xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>66.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>My Custom Trade Planning</masterLabel>
   <targets>
        <target>lightning__AppPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__AppPage,lightning__RecordPage,lightning__HomePage">
            <property name="productFields" type="String"
              label="Account Plan - Product Fields in CSV Download"
              description="JSON array of Product2 field API names for the Account Plan P&L CSV download."
              default='["Description_1__c"]' />
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>
 

Reference—Every Slot, Event, and EAR Code

Slots (on cgcloud-tpm-trade-planning)

  • icon
  • title
  • breadcrumbs
  • subtitle
  • left-buttons
  • center-buttons
  • right-buttons
  • fullheight-buttons

Outbound Events

Every event is emitted by the inner BO LWC (Trade Calendar: <cgcloud-tpm-trade-planning-b-o>, Account Plan: <cgcloud-tpm-account-plan-b-o>) and redispatched on the outer <cgcloud-tpm-trade-planning> component so that wrappers can listen at either level.

  • statuschange
  • internalreactapphasrenderedchange
  • viewchange
  • viewlistchange
  • viewnamechange
  • showfilterchange
  • isfiltersetchange
  • canaccessplchange
  • haspromotioncreateaccesschange
  • enableprintchange
  • enablecopypromotionchange
  • calcstatuschange
  • isgriddirtychange
  • modifiedviewchange
  • pageearightschange
  • gearactiontoreopenchange
  • promotionlistchange
  • downloadinggridchange
  • loadinggridchange
  • treedatachange
  • accountplandownloadbuttonenabledchange

EAR Codes

All EAR codes are passed to setEARight(), isVisible(), or isEditable() on <cgcloud-tpm-trade-planning>. The wrapper routes codes by prefix.

  • Trade Calendar (TP_*, routed to Trade Calendar BO): TP_REFRESH, TP_FILTER, TP_VIEW_CONTROLS, TP_PRINT, TP_PL, TP_COPY_PROMOTION, TP_NEW_PROMOTION
  • Account Plan (AP_*, routed to Account Plan BO): AP_DOWNLOAD, AP_NEW_PROMOTION, AP_FILTER, AP_VIEW_CONTROLS

Imperative @api Methods (on cgcloud-tpm-trade-planning)

  • refresh()
  • print()
  • newPromotion()
  • copyPromotion()
  • download()
  • goToAccountPlan()
  • goToTradeCalendar()
  • toggleFilter()
  • selectView()
  • runViewAction()
  • getProperty()
  • setProperty()
  • setEARight()
  • isVisible()
  • isEditable()
  • getActiveBusinessObject()
  • getGridStatus()
 
Loading
Salesforce Help | Article