function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JohnDuraiJohnDurai 

calling Apex class in LWC Button

Hi All - I just want to call the apex method which has two paramaeters in when on click button. I have created the Button using LWC and trying to call the apex method , below is my code. can someone correct me if my approach is correct. New to LWC trying to implement this want best way and suggestions.

Apex Method :
@AuraEnabled(cacheable=true)
    public static void recountAssets(Id b2bAccountId, Id b2bOrderId){
        String sDISCOCouponCode;
        List<Id> lstB2BOrderIds = new List<Id>();
        List<String> lstPkgDefCodes = new List<String>();
        List<OrderItem> lstB2BOrderItems = new List<OrderItem>(); //List of all B2B Order Items that requires reconciliation
        //List<Order> lstB2BOrders = new List<Order>();//List of all B2B Orders that requires reconciliation
        
        
        if(b2bAccountId != null){
            Account objB2BAccount = [SELECT ID, DISCOCouponCode__c FROM Account WHERE ID =: b2bAccountId AND RecordType.DeveloperName = 'ACC_B2BCustomer' LIMIT 1];
            if(objB2BAccount != null){
                sDISCOCouponCode = objB2BAccount.DISCOCouponCode__c;
                if(!String.isEmpty(sDISCOCouponCode)){
                    if(b2bOrderId != null){
                        // for(Order o:b2bOrders){
                        //     lstB2BOrderIds.add(o.Id);
                        //     system.debug('lstB2BOrderIds' +lstB2BOrderIds);
                        // }
                        
                        lstB2BOrderItems = [SELECT  Id, OrderId, Package_Definition_Code__c, DISCOCouponCode__c, NoOfActiveSubscriptionsExclBuffer__c, Quantity, Order.NumberOfDigitalSubscriptionSold__c
                            FROM OrderItem WHERE TECH_OrderCategory__c ='Corporate' AND (OrderId =: b2bOrderId OR Order.Original_Subscription__r.Id =: b2bOrderId) AND DISCOCouponCode__c =: sDISCOCouponCode AND Order.Status = 'ACTIVE' AND Order.StartDate__c <= TODAY AND Order.End_Date__c >= TODAY AND Order.B2BProduct__c != 'Anonymous' ORDER BY Order.StartDate__c ASC];
                        system.debug('lstB2BOrderItems' +lstB2BOrderItems);
                    }
                    else{
                        lstB2BOrderItems = [SELECT  Id, OrderId, Package_Definition_Code__c, DISCOCouponCode__c, NoOfActiveSubscriptionsExclBuffer__c, Quantity, Order.NumberOfDigitalSubscriptionSold__c
                            FROM OrderItem WHERE TECH_OrderCategory__c ='Corporate' AND DISCOCouponCode__c =: sDISCOCouponCode AND Order.Status = 'ACTIVE' AND Order.StartDate__c <= TODAY AND Order.End_Date__c >= TODAY AND Order.B2BProduct__c != 'Anonymous' ORDER BY Order.StartDate__c ASC];
                    }

                    // lstB2BOrderIds.clear(); //Repurposing the variable for further use
                    // system.debug('lstB2BOrderIds' +lstB2BOrderIds);
                    if(lstB2BOrderItems.size()>0){
                        
                        for(OrderItem oi:lstB2BOrderItems){
                            lstPkgDefCodes.add(oi.Package_Definition_Code__c); //Prepare the list of package definition codes
                            lstB2BOrderIds.add(oi.OrderId); //Prepare the list of ids of all the B2B orders that will go through active sub count reconciliation
                            oi.NoOfActiveSubscriptionsExclBuffer__c = 0; //Reset the current asset count
                            system.debug(' oi.NoOfActiveSubscriptionsExclBuffer__c ' + oi.NoOfActiveSubscriptionsExclBuffer__c);
                        }
                    }

                    if(lstPkgDefCodes.size()>0){
                        Map<String, Decimal> mapActiveAssetCount = new Map<String, Decimal>(); //Count of all the active assets that requires recounting, grouped by Package Definition Code
                        List<Asset> lstActiveAssets = [SELECT Package_Definition_Code__c, Id FROM Asset
                            WHERE Package_Definition_Code__c IN: lstPkgDefCodes AND Order_Product__r.DISCOCouponCode__c =: sDISCOCouponCode AND Status = 'ACTIVE'];
                        for (Asset a : lstActiveAssets)  {
                            if(mapActiveAssetCount.containsKey(a.Package_Definition_Code__c)){
                                //System.debug('a.Package_Definition_Code__c : ' + a.Package_Definition_Code__c );
                                Decimal nAssetCount = (Decimal) mapActiveAssetCount.get(a.Package_Definition_Code__c);
                                nAssetCount++;
                                system.debug('nAssetCount' +nAssetCount);
                                mapActiveAssetCount.put(a.Package_Definition_Code__c, nAssetCount);
                            }
                            else{
                                mapActiveAssetCount.put(a.Package_Definition_Code__c, 1);
                            }
                        }

                        Map<Id,Decimal> mapTotalActiveSubsInB2BOrder = new map<Id,Decimal>();
                        for(OrderItem oi:lstB2BOrderItems){
                            Decimal nB2BOrderTotalActiveSubs;
                            if(mapTotalActiveSubsInB2BOrder.containsKey(oi.OrderId)){
                                nB2BOrderTotalActiveSubs = mapTotalActiveSubsInB2BOrder.get(oi.OrderId);
                                system.debug('nB2BOrderTotalActiveSubs' +nB2BOrderTotalActiveSubs);
                            }
                            else{
                                nB2BOrderTotalActiveSubs = 0;
                                system.debug('nB2BOrderTotalActiveSubs' +nB2BOrderTotalActiveSubs);
                            }

                            if(mapActiveAssetCount.containsKey(oi.Package_Definition_Code__c)){
                                Decimal nCurrentAssetCountByPkgDefCode = (Decimal) mapActiveAssetCount.get(oi.Package_Definition_Code__c);
                                system.debug('nCurrentAssetCountByPkgDefCode' +nCurrentAssetCountByPkgDefCode);
                                if(nCurrentAssetCountByPkgDefCode > 0){
                                    // System.debug('Package_Definition_Code__c : ' + oi.Package_Definition_Code__c );
                                    // System.debug('nCurrentAssetCountByPkgDefCode : ' + nCurrentAssetCountByPkgDefCode );
                                    
                                    // System.debug('Order.NumberOfDigitalSubscriptionSold__c : ' + oi.Order.NumberOfDigitalSubscriptionSold__c );
                                    // System.debug('nB2BOrderTotalActiveSubs : ' + nB2BOrderTotalActiveSubs );
                                    
                                    if((oi.Order.NumberOfDigitalSubscriptionSold__c >= nCurrentAssetCountByPkgDefCode) && (nB2BOrderTotalActiveSubs < nCurrentAssetCountByPkgDefCode)){
                                        Decimal nCountUp = nCurrentAssetCountByPkgDefCode - nB2BOrderTotalActiveSubs;
                                        oi.NoOfActiveSubscriptionsExclBuffer__c += nCountUp;
                                        nB2BOrderTotalActiveSubs += nCountUp;
                                        nCurrentAssetCountByPkgDefCode -= nCountUp;
                                        system.debug('nCountUp' +nCountUp);
                                    }
                                    else if((oi.Order.NumberOfDigitalSubscriptionSold__c < nCurrentAssetCountByPkgDefCode) && (nB2BOrderTotalActiveSubs < oi.Order.NumberOfDigitalSubscriptionSold__c)){
                                        Decimal nCountUp = oi.Order.NumberOfDigitalSubscriptionSold__c - nB2BOrderTotalActiveSubs;
                                        oi.NoOfActiveSubscriptionsExclBuffer__c += nCountUp;
                                        nB2BOrderTotalActiveSubs += nCountUp;
                                        nCurrentAssetCountByPkgDefCode -= nCountUp;
                                        system.debug('nCountUp' +nCountUp);
                                    }
                                    mapTotalActiveSubsInB2BOrder.put(oi.OrderId, nB2BOrderTotalActiveSubs);
                                    mapActiveAssetCount.put(oi.Package_Definition_Code__c, nCurrentAssetCountByPkgDefCode);
                                }
                            }
                        }

                        update lstB2BOrderItems;
                        system.debug('lstB2BOrderItems' +lstB2BOrderItems);

                        //Reconciling NumberofDigitalSubscriptionsActive__c in B2B Orders
                        if(lstB2BOrderIds.size()>0){
                            List<Order> lstB2BOrders = [SELECT Id, NumberofDigitalSubscriptionsActive__c, TECH_TotalNumberofActiveSubscription__c FROM Order WHERE Id IN: lstB2BOrderIds];
                            system.debug('lstB2BOrders' +lstB2BOrders);
                            if(lstB2BOrders.size()>0){
                                for(Order o : lstB2BOrders){
                                    o.NumberofDigitalSubscriptionsActive__c = o.TECH_TotalNumberofActiveSubscription__c;
                                }
                                update lstB2BOrders;
                            }
                        }
                    }
                }
            }
        }


LWC JS:
import { LightningElement,track  } from 'lwc';
import recountAssets from '@salesforce/apex/B2BActiveAssetsRecountHandler.recountAssets';
export default class ReCountMechforAssetManagement extends LightningElement {
    clickedButtonLabel;
    @track b2bAccountId;
    @track b2bOrderId;
    @track error;
    handleClick(event) {
        this.clickedButtonLabel = event.target.value;
        recountAssets()
        .then(result =>{
            this.b2bAccountId = result;
            this.b2bOrderId = result;
        })
        .catch(error => {
            this.error = error;
        });
        //this.clickedButtonLabel = event.target.label;
    }
}

HTML:

<template>
    <div class="slds-m-top_small slds-m-bottom_medium">
        <!-- Brand outline variant: Identifies the primary action in a group of buttons, but has a lighter look -->
        <lightning-button variant="brand-outline" label="Recount" title="Primary action with lighter look" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
    </div>
</template>
</template>

Best Answer chosen by JohnDurai
CharuDuttCharuDutt

Hii John 

Try Below Code I've Modified It
 

import { LightningElement, api, track, wire } from 'lwc';
import recountAssets from '@salesforce/apex/B2BActiveAssetsRecountHandler.recountAssets';
import { getRecord} from "lightning/uiRecordApi";
import AccountId from '@salesforce/schema/Order.AccountId';
import Id from '@salesforce/schema/Order.Id';
const FIELDS = ['Order.AccountId', 'Order.Id'];
export default class PracticeComponent extends LightningElement {
  
 @api recordId;
    AccId;
    OrderId;
    orderrec;//Will Be Used To Pass Parameter AccountId And Order From it

    @wire( getRecord, { recordId: '$recordId', fields: FIELDS } )
    wiredRecord({ error, data }) {

        if ( error ) {
            let message = 'Unknown error';
            if (Array.isArray(error.body)) {
                message = error.body.map(e => e.message).join(', ');
            } else if (typeof error.body.message === 'string') {
                message = error.body.message;
            }
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error loading contact',
                    message,
                    variant: 'error',
                }),
            );

        } else if ( data ) {

            this.orderrec= data;
            console.log( 'Orderis ' + JSON.stringify( this.orderrec) );
            this.AccId = this.orderrec.fields.AccountId.value;
            this.OrderId = this.orderrec.fields.Id.value;

        }
    }
 handleClick(event) {
     const AccountId = this.AccId;
     const OrderId = this.OrderId;
    recountAssets({ b2bAccountId: AccountId,
            b2bOrderId: OrderId})
            .then((result)=>{
               console.log(JSON.stringify(result));
            })
            .catch((error)=>{
                console.log(error);
        });
    }
}
Please Mark It As Best Asnwer If It Helps
Thank You!

All Answers

CharuDuttCharuDutt
Hii John 
Try Below Code
<template>
    <div class="slds-m-top_small slds-m-bottom_medium">
        <!-- Brand outline variant: Identifies the primary action in a group of buttons, but has a lighter look -->
        <lightning-button variant="brand-outline" label="Recount" title="Primary action with lighter look" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
    </div>
</template>
</template>



import { LightningElement, api, track, wire } from 'lwc';
import recountAssets from '@salesforce/apex/B2BActiveAssetsRecountHandler.recountAssets';
import AccountId from '@salesforce/schema/Order.AccountId';
import Id from '@salesforce/schema/Order.Id';
const FIELDS = ['Order.AccountId', 'Order.Id'];
export default class PracticeComponent extends LightningElement {
  
 @api recordId;
    AccId;
    OrderId;


    @wire( getRecord, { recordId: '$recordId', fields: FIELDS } )
    wiredRecord({ error, data }) {

        if ( error ) {
            let message = 'Unknown error';
            if (Array.isArray(error.body)) {
                message = error.body.map(e => e.message).join(', ');
            } else if (typeof error.body.message === 'string') {
                message = error.body.message;
            }
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error loading contact',
                    message,
                    variant: 'error',
                }),
            );

        } else if ( data ) {

            this.contact = data;
            console.log( 'Contact is ' + JSON.stringify( this.contact ) );
            this.AccId = this.contact.fields.AccountId.value;
            this.OrderId = this.contact.fields.Id.value;

        }
    }
 handleClick(event) {
     const AccountId = this.AccId;
     const OrderId = this.OrderId;
    recountAssets({ b2bAccountId: AccountId,
            b2bOrderId: OrderId})
            .then((result)=>{
               console.log(JSON.stringify(result));
            })
            .catch((error)=>{
                console.log(error);
        });
    }
}
Please Mark It As Best Asnwer If It Helps
Thank You!
JohnDuraiJohnDurai
Thanks @CharuDutt, Just want to know why this.contact is used here? because there I am not going to user Contact anywhere
JohnDuraiJohnDurai
Also while Deploying I am gettig the below error.
 LWC1503: "getRecord" is not a known adapter. (13:12)
JohnDuraiJohnDurai
Thanks @charuDutt, just want to know why this.contact is used here, because there I am not going to use contact anywhere. Also while deploying i am getting the below error. "gerRecord" is not a known adapter. Could you please help here. Thanks!
CharuDuttCharuDutt

Hii John 

Try Below Code I've Modified It
 

import { LightningElement, api, track, wire } from 'lwc';
import recountAssets from '@salesforce/apex/B2BActiveAssetsRecountHandler.recountAssets';
import { getRecord} from "lightning/uiRecordApi";
import AccountId from '@salesforce/schema/Order.AccountId';
import Id from '@salesforce/schema/Order.Id';
const FIELDS = ['Order.AccountId', 'Order.Id'];
export default class PracticeComponent extends LightningElement {
  
 @api recordId;
    AccId;
    OrderId;
    orderrec;//Will Be Used To Pass Parameter AccountId And Order From it

    @wire( getRecord, { recordId: '$recordId', fields: FIELDS } )
    wiredRecord({ error, data }) {

        if ( error ) {
            let message = 'Unknown error';
            if (Array.isArray(error.body)) {
                message = error.body.map(e => e.message).join(', ');
            } else if (typeof error.body.message === 'string') {
                message = error.body.message;
            }
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error loading contact',
                    message,
                    variant: 'error',
                }),
            );

        } else if ( data ) {

            this.orderrec= data;
            console.log( 'Orderis ' + JSON.stringify( this.orderrec) );
            this.AccId = this.orderrec.fields.AccountId.value;
            this.OrderId = this.orderrec.fields.Id.value;

        }
    }
 handleClick(event) {
     const AccountId = this.AccId;
     const OrderId = this.OrderId;
    recountAssets({ b2bAccountId: AccountId,
            b2bOrderId: OrderId})
            .then((result)=>{
               console.log(JSON.stringify(result));
            })
            .catch((error)=>{
                console.log(error);
        });
    }
}
Please Mark It As Best Asnwer If It Helps
Thank You!
This was selected as the best answer
JohnDuraiJohnDurai
@charuDutt - I am getting the below error on placing the button in record page.
User-added image
JohnDuraiJohnDurai
@charuDutt - I am getting the below error on placing the button in record page.
SushilBolwarSushilBolwar
@JohnDurai in the code given by @charuDutt, add the below import 
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

 
JohnDuraiJohnDurai
Thanks @sushnil Bolwar 10 @@charuDutt It works now, but i could place this button only in Order object record page, if i place it in account object record page i am facing the below error. The "fields" query string parameter contained object api names that do not correspond to the apo names of any of the requested records IDs. The requested object api names were: [order], while the requested records had object types: [Account]. Also how to place this button in page layout.
CharuDuttCharuDutt
Hii John It Will WOrk Only On Order Cause From Order Record It Will Get Order Id Ans AccountId And Pass it Ass Parameter I Apex class

Please Close your Query By Marking It As best Answer So it Also helps Others As Well I  Future
Pavlo MartovichPavlo Martovich
@CharuDutt It is amazing solutions! Thank you a lot!