• Mahesh Gorrepati
  • NEWBIE
  • 30 Points
  • Member since 2022

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 16
    Questions
  • 30
    Replies
Hii EveryOne,
i have a apex class
public class class1{
     Public static list<string> method1(list<string> Param1){
          list<strings> messsages = new list<string> ();
           for(  String S : Param1){
              // Class2.method2(s)  will return a list  of strings
                messsages.add(Class2.method2(s);
             }
return  messsages;
       }
}

I created  a LWC component in which above  method( class1.method1) is invoked IMperatively In javascript file
eg:-
 in the .then block code after the promise is done is executing.
the returned list strings from the apex class is showd as a promise Object In console.



Kindly help here
can we make method name in a test class same as class name for test class in apex salesforce
Query:-
 1. We can invoke only method with @WIRE Decorator.
  2. IMperative method invoke is not passible directly

I got the  information using chatGPT


you cannot directly invoke an Apex class from an Experience Site in a Lightning Web Component (LWC). Experience Sites are designed to provide a public-facing website experience for external users and do not have direct access to Apex code.
However, you can leverage Salesforce APIs to interact with your Apex code indirectly. You can create a custom Apex REST or SOAP web service that encapsulates the functionality you want to invoke. Then, from your LWC component hosted on the Experience Site, you can make HTTP requests to that custom web service to perform the desired actions.
Here's a general outline of the steps involved:
Create a custom Apex class that exposes the desired functionality as a REST or SOAP web service.
Configure the necessary access permissions for the custom web service to be accessible from the Experience Site's guest user profile.
In your LWC component, use the standard fetch() or XMLHttpRequest API to make an HTTP request to the custom web service endpoint.
Handle the response from the web service in your LWC component and update the UI accordingly.
By following this approach, you can indirectly invoke the functionality of your Apex class from the LWC component hosted on the Experience Site.

Kindly Help Here

 
CLASS:- 
  @RestResource(urlMapping='/Razorpay/*')
global class WebhooK_for_RazorPay 
{
    
@HttpPost
    global static void ResponseFromPaymentLInk()
    {
        
        
        RestRequest request = RestContext.request;
        system.debug('The request '+  request );
        RestResponse response = RestContext.response;
           system.debug('The response '+  response );
        
    }
     
}

Webhook URL:- https://techforceservices18-dev-ed.develop.my.site.com/services/apexrest/Razorpay

used in Razorpay 
How can we  show images in the Experience cloud site  which are having the URL in  the field of an Object using LWC component and it should using img tag  ?
 
can we create other methods in batch class of an apex apart from start , execute and finish methods?
User-added image
Error in Save call back:
{status: 500, body: {…}, headers: {…}, ok: false, statusText: 'Server Error', …}
body: {message: 'Unable to read SObject'}
errorType: "fetchResponse"
headers: {}
ok: false
status: 500
statusText: "Server Error"
[[Prototype]]: Object




LWC html file:-
<template>
    <lightning-card>
        <lightning-button-icon icon-name="utility:add" slot="actions" onclick={addRow}></lightning-button-icon>
    <lightning-button
        label={toggleSaveLabel}
        icon-name="utility:save"
        slot="actions"
        onclick={handleSave}>
    </lightning-button>
    <lightning-button
        label="Clear All"
        icon-name="utility:clear"
        slot="actions"
        onclick={taskRecords}>
    </lightning-button>
        <table class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered" aria-label="Example table of Opportunities with vertical borders">
            <thead>
            <tr class="slds-line-height_reset">
                <th class="" scope="col">
                    <div class="slds-truncate" title="SI NO">SI.No</div>
                    </th>
            <th class="" scope="col">
               
            <div class="slds-truncate" title="Operator  Name">Operator_Name</div>
            </th>
            <th class="" scope="col">
            <div class="slds-truncate" title="Activities">Activities</div>
            </th>
            <th class="" scope="col">
            <div class="slds-truncate" title="Actual Start Date">Actual_Start_Date_time</div>
            </th>  
            <th class="" scope="col">
            <div class="slds-truncate" title="Actual End date">Actual_End_date_time</div>
            </th>
            <th class="" scope="col">
            <div class="slds-truncate" title="TOtal Hours">Total_Hours</div>
            </th>
            <th class="" scope="col">
             <div class="slds-truncate" title="Remarks">Remarks</div>
             </th>
            </tr>
            </thead>
            <tbody>
                <template for:each={taskList} for:item="tsk" for:index="index">
                    <tr key={tsk.key}>
                        <td>{index}</td>                                                  
                        <td>
                            <!--<div class="slds-box slds-p-top_small" style="background-color: white;">
                                <lightning-record-edit-form object-api-name="Contact" >
                                    <lightning-input-field field-name="WhoId" variant="label-hidden"  value={tsk.Name} onchange={handleoperatornameChange} > </lightning-input-field>
                                </lightning-record-edit-form>
                            </div>
                            <lightning-record-edit-form object-api-name="Task" >
                                <lightning-input-field field-name='WhoId' onchange={handleoperatornameChange}></lightning-input-field>
                              </lightning-record-edit-form>    
                              <lightning-record-edit-form object-api-name="Task"  >
                                <lightning-input-field field-name="WhoId" variant="label-hidden" onchange={handleAccountSelection} required> </lightning-input-field>
                            </lightning-record-edit-form> -->
                            <lightning-input label=" "  key={tsk.key} data-id={tsk.key} type="text" value={tsk.operatorname} onchange={handleoperatornameChange}></lightning-input>                        
                        </td>
                        <td>
                            <lightning-input label=" "   key={tsk.key} data-id={tsk.key} type="text" value={tsk.Activities} onchange={handleActivitiesChange}></lightning-input>                        
                        </td>
                        <td>
                            <lightning-input label=""  key={tsk.key} data-id={tsk.key} type="datetime" value={tsk.acstarttime} onchange={handleacstarttimeChange}></lightning-input>
                        </td>
                        <td>
                            <lightning-input lable=""  key={tsk.key} data-id={tsk.key} type="datetime" value={tsk.acendtime} onchange={handleacendtimechange}> </lightning-input>
                        </td>
                        <td>
                            <lightning-input lable=""  key={tsk.key} data-id={tsk.key} type="number"  value={tsk.totalHours}></lightning-input>
                        </td>
                        <td>
                            <lightning-input label=""  key={tsk.key} data-id={tsk.key} type="text" value={tsk.remarks} onchange={handleremarkschange}></lightning-input>
                        </td>
                        <td>
                            <a onclick={removeRow}>
                                <lightning-icon icon-name="utility:delete" size="small" style="margin-top: -4px; margin-right: 0px;" ></lightning-icon>
                                <span class="slds-assistive-text">Delete</span>
                            </a>
                        </td>
                    </tr>
                </template>
        </tbody>
            </table>
    </lightning-card>
</template>

LWC JS file :;-

import { LightningElement,track,api,wire } from 'lwc';
import {getRecord,getFieldValue} from 'lightning/uiRecordApi';
import inserttasks from '@salesforce/apex/Taskforoperators.inserttasks';
import ACTUAL_END_TIME from '@salesforce/schema/task.Actual_end_date_time__c';
import ACTUAL_START_TIME from '@salesforce/schema/task.Actual_start_Date_and_time__c';
import REMARKS_FIELD from '@salesforce/schema/task.CallObject';
import ACTIVITIES_FIELD from '@salesforce/schema/task.Description';
import  NAME_FIELD from '@salesforce/schema/task.CallDisposition';
import  NAME_FIELDS from '@salesforce/schema/Contact.Name' ;
const fields = [NAME_FIELDS];
export default class AddTasksToOperators extends LightningElement {
//@track operatorname;
//@track activities;
//@track acstarttime;
//@track acendtime;
//@track totalHours;
//@track remarks;
@track taskList=[];


//
handleoperatornameChange(event)
{
    let foundelement = this.taskList.find(ele => ele.key == event.target.dataset.id);
        foundelement.Operator_Name = event.target.value;
        this.taskList = [...this.taskList];
        //this.operatorname=event.target.value;
        // this.lookupId = event.target.value;
       
        console.log(event.target.value); // "001***************"
        //console.log(event.detail.value[0]); // "001***************"
}
handleActivitiesChange(event)
{
    let foundelement = this.taskList.find(ele => ele.key == event.target.dataset.id);
    foundelement.Activities = event.target.value;
    this.taskList = [...this.taskList];
}
handleacstarttimeChange(event)
{
    let foundelement = this.taskList.find(ele => ele.key == event.target.dataset.id);
        foundelement.Actual_Start_Date_time = event.target.value;
        this.taskList = [...this.taskList];
}
handleacendtimechange(event)
{
    let foundelement = this.taskList.find(ele => ele.key == event.target.dataset.id);
        foundelement.Actual_End_date_time = event.target.value;
        this.taskList = [...this.taskList];
}
handleremarkschange(event)
{
    let foundelement = this.taskList.find(ele => ele.key == event.target.dataset.id);
        foundelement.Remarks = event.target.value;
        this.taskList = [...this.taskList];
}
connectedCallback()
{
this.taskRecords()  
}
taskRecords()
{
    this.taskList=[];
    for(var i=0; i < 4 ; i++){
        this.taskList.push({Operator_Name : NAME_FIELD,Activities : ACTIVITIES_FIELD,Actual_Start_Date_time : ACTUAL_START_TIME,Actual_End_date_time : ACTUAL_END_TIME,Remarks : REMARKS_FIELD,key : Math.random().toString(36).substring(2, 15)});
    }
}
addRow()
{
console.log('New rrow is added')
this.taskList.push({Operator_Name : NAME_FIELD,Activities : ACTIVITIES_FIELD,Actual_Start_Date_time : ACTUAL_START_TIME,Actual_End_date_time : ACTUAL_END_TIME,Remarks : REMARKS_FIELD,key : Math.random().toString(36).substring(2, 15)})
}
removeRow(event)
{
    const indexPos = event.currentTarget.name;
    let remList = [];
    remList = this.taskList;
    remList.splice(indexPos,1);
    this.taskList = remList;
}
handleSave()
{
    let toSaveList = this.taskList.slice(0);
       
        console.log( ' Final Save ==> ' + JSON.stringify(toSaveList));
    console.log('save invoked  Log');
    // console.log('this.tasks for the apex' +toSaveList);
inserttasks({lsttasks : toSaveList})
.then(() => {
    console.log('Success Log');
    this.dispatchEvent(
        new ShowToastEvent({
            title : 'Success',
            message : `Records saved succesfully!`,
            variant : 'success',
        }),
    )
    this.taskRecords();
    this.error = undefined;
})
.catch(error => {
    this.error = error;
    this.record = undefined;
    console.log("Error in Save call back:", this.error);
})
}

}

Class code:-
public with sharing class Taskforoperators {
  @AuraEnabled
    public static string  inserttasks(list<Task> lsttasks){
        system.debug('the lsits' + lsttasks);
        string response='';
try {
    list<task> newtasks = new list<task> ();
    for (task tsk :lsttasks )
    {
        tsk.Subject='Other';
        tsk.Status='Not Started';
        tsk.Priority='Normal';
        //tsk.WhatId=relatedId;
        tsk.OwnerId=userInfo.getUserId();
        
        newtasks.add(tsk);
    }
    if(!newtasks.isEmpty()){
        insert newtasks;
        response='SUCCESS';
    }
    
} catch (Exception e) {
    System.debug(e.getMessage());
    response=e.getMessage();
}
return response;
    }

    
}
ERROR:-
System.JSONException: Malformed JSON: Expected '{' at the beginning of object
[{"errorCode":"METHOD_NOT_ALLOWED","message":"HTTP Method 'POST' not allowed. Allowed are "}]


please click here (https://docs.google.com/document/d/17YS8gnUiZ1s_HAzvDUb8LwKUvdKLEFK0nX60mnllc7U/edit)kindly check the below docs fir the code

 
ERROR:-16:20:52:632 USER_DEBUG [67]|DEBUG|[{"message":"Unexpected parameter encountered during deserialization: Amount__c at [line:1, column:15]","errorCode":"JSON_PARSER_ERROR"}]

Code:-
public class paymentfromsalesforce {
   
    
    public  static  string apiclientid;
    public  static  string apiclientsecrete;
    public  static  string username;
    public  static  string  password;
    
    public static void getAuthCreds()
    {
        salesforcefromsalesforce__c clientid = salesforcefromsalesforce__c.getInstance('Client ID');
        salesforcefromsalesforce__c clientsecreate = salesforcefromsalesforce__c.getInstance('client secret');
        salesforcefromsalesforce__c clientusername = salesforcefromsalesforce__c.getInstance('username');
        salesforcefromsalesforce__c clientpassword = salesforcefromsalesforce__c.getInstance('password');
        
        apiclientid = clientid.value__c;
        apiclientsecrete =clientsecreate.value__c;
        username  =  clientusername.value__c;
        PASSWORD  = clientpassword.value__c;
    }
   public class deserializeResponse
    {
        public String id {set;get;}
        public String access_token {set;get;}
        public string typeofpayment {set;get;}
        public integer payamount {set;get;}
        public string paymethod {set;get;}
    }
    public String ReturnAccessToken (paymentfromsalesforce acount)
    {
        // method used authoentication details in the system. 
        getAuthCreds();
        
        String reqbody = 'grant_type=password'+'&client_id='+apiclientid+'&client_secret='+apiclientsecrete+'&username='+username+'&password='+PASSWORD;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
        req.setEndpoint('https://vignesh9666-dev-ed.my.salesforce.com/services/oauth2/token');
        HttpResponse res = h.send(req);
        system.debug('The access token for the ' + res.getBody());
        deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
        system.debug('The access token for the ' + resp1.access_token);
        return resp1.access_token;
    }

 @AuraEnabled 
 public static deserializeResponse createpayment(String ptype, integer pamount, String pstatus)
 {
  paymentfromsalesforce acount = new paymentfromsalesforce();
  String accessToken = acount.ReturnAccessToken (acount);
 
  if(accessToken != null)
  {
   
      HttpRequest req1=new HttpRequest();
            req1.setEndpoint('https://vignesh9666-dev-ed.my.salesforce.com/services/apexrest/mypaymentgateway/');
            req1.setMethod('POST');
           req1.setHeader('Content-Type','application/json');
           req1.setHeader('Accept','application/json');
          req1.setHeader('Authorization','Bearer '+accessToken);
            req1.setBody( '{"Amount__c":"' +pamount+ '"}');
            Http http1=new Http();
            HttpResponse res1=new HttpResponse();
            res1=http1.send(req1);        
            System.debug(res1.getStatusCode());
            System.debug(res1.getBody()); 
      
      deserializeResponse resp2 = (deserializeResponse)JSON.deserialize(res1.getbody(),deserializeResponse.class);
      
      system.debug('The record id is ' + resp2.id);
  }
     return resp2;
 }
   
}

webservices code from another org:-

@RestResource(urlMapping='/mypaymentgateway/*')

Global class newpaymentgatewayrcord {
     @HttpPost
    global static id paymentrecords(string ptype, integer pamount, string pstatus)
    {
        Payment_Gateway__c pay = new Payment_Gateway__c();
         
        pay.TYPE__c=ptype;
            pay.Amount__c=pamount;
            pay.Status__c=pstatus;
        
            insert pay;
        
        return pay.id;
    }

}


 
I want to integrate  any payment method with salesforce. but  i gone through different blogs and sites in the web,
but, i didn't find any documnetation about the request sending and response getting  fromt he paymnet gateway.
 If references, it  will be helpful.
  thanks

Code:-

public class Getaccounts_from_B {

    

    public  static  string apiclientid;

    public  static  string apiclientsecrete;

    public  static  string username;

    public  static  string  password;

    

    public static void getAuthCreds()

    {

        salesforcetosalesforce__c clientid = salesforcetosalesforce__c.getInstance('Client ID');

        salesforcetosalesforce__c clientsecreate = salesforcetosalesforce__c.getInstance('Client secrete');

        salesforcetosalesforce__c clientusername = salesforcetosalesforce__c.getInstance('Username');

        salesforcetosalesforce__c clientpassword = salesforcetosalesforce__c.getInstance('password');

        

        apiclientid = clientid.value__c;

        apiclientsecrete =clientsecreate.value__c;

        username  =  clientusername.value__c;

        PASSWORD  = clientpassword.value__c;

    }

    public class deserializeResponse

    {

        public String id;

        public String access_token;

    }

    public static  String ReturnAccessToken ()

    {

        // method used authoentication details in the system. 

        getAuthCreds();

        

        String reqbody = 'grant_type=password'+'&client_id='+apiclientid+'&client_secret='+apiclientsecrete+'&username='+username+'&password='+PASSWORD;

        Http h = new Http();

        HttpRequest req = new HttpRequest();

        req.setBody(reqbody);

        req.setMethod('POST');

        req.setEndpoint('https://nichebit6-dev-ed.develop.my.salesforce.com/services/oauth2/token');

        HttpResponse res = h.send(req);

        system.debug('The access token for the ' + res.getBody());

        deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);

        system.debug('The access token for the ' + resp1.access_token);

        return resp1.access_token;

    }

}


Tried:- I have gone through web, they mentioned to change 

  1.  change "IP Relaxation" setting to "Relax IP Restrictions"
  2.  Access of the connect app:- it is also changed to self authorization.
 

Note:- i tried the solutions above, but the code is showing the same error. Kindly suggest any  other method to resolve the issue.


 
How can we approve multiple records from approval process at once in salesforce?
  usinfg code or any other method.
list<Account> acctoupdate = [select id,name,Active_policies__c,    Expired_policies__c,Expiring_policies__c,
                                             (select id,name,customer_name__c,    plan_status__c from customer_policy_details__r where id in:newrecords.keyset() All rows)
                                             from account where id in: accountids];
trigger code:;-if(trigger.isafter && trigger.isupdate)
    {
        for(customer_policy_detail__c csold: trigger.old)
        {
            for(customer_policy_detail__c csnew : trigger.new)
            {
                if(csold.plan_status__c=='new'&& csnew.plan_status__c=='active'||csold.plan_status__c=='active'&& csnew.plan_status__c=='expired' ||
                  csold.plan_status__c=='expired'&& csnew.plan_status__c=='active')
                {
                   policystatus_to_noof_policies_on_account.updationofrecords(trigger.newmap,trigger.oldmap);
                       }
                       else if(csold.plan_status__c!=csnew.plan_status__c)
                   {
                       csnew.adderror('you can change the plan status field from'+ csold.plan_status__c+ 'to'+ csnew.plan_status__c )    ;  
                }
            
        }
    }
    }
method code:- for updation of records

/*public static void updationofrecords(map<id,customer_policy_detail__c> newrecords,map<id,customer_policy_detail__c> oldrecords )
    {
        // Get account record id from the new records. 
        set<id> accountids = new set<id>();
        if(newrecords!=null && !newrecords.isempty())
        {   
            for(customer_policy_detail__c cr :newrecords.values())
            {
                accountids.add(cr.Customer_Name__c);
            }
            // store the oldrecords inside the map collection
            map<id,customer_policy_detail__c> csoldrecords =oldrecords; 
            
            // check account id is empty or not
            if(!accountids.isempty()){
                // query to the the related account records
                list<Account> acctoupdate = [select id,name,Active_policies__c,    Expired_policies__c,Expiring_policies__c,
                                             (select id,name,customer_name__c,    plan_status__c from customer_policy_details__r where id in:newrecords.keyset())
                                             from account where id in: accountids];
                
                
                // define map to restrict for the system.listexeception : duplicateid list error
                map<id,account> updateaccount =new map<id,account>();
                //list collection to bulkify 
                //list<account> lstaccount = new list<account> ();
                if(!acctoupdate.isempty()){
                    
                    for(Account acc: acctoupdate){
                        // add null check on the related collection
                        if(acc.customer_policy_details__r!=null && !acc.customer_policy_details__r.isempty())  {
                            for(customer_policy_detail__c cs:acc.customer_policy_details__r){
                                
                                // getting the old record with the id from the current record
                                list<customer_policy_detail__c> csold =csoldrecords.get(cs.Id);
                                
                                if(csold.plan_status__c =='new'&& cs.plan_status__c=='active'){
                                    system.debug( 'the active policies count'+acc.Active_policies__c);
                                    // here it will get the previous value of the accountpolicies field and add the new records count to the number
                                    if(acc.Active_policies__c==null){
                                        acc.Active_policies__c=0;
                                    }
                                    acc.Active_policies__c+=1;
                                } 
                                // comparing the old plan status to the current status field 
                                else if (csold.plan_status__c =='active'&& cs.plan_status__c=='expired'){
                                    // here it will get the previous value of the expiredpolicies field and add the new records count to the number
                                    acc.Active_policies__c-=1;
                                   if(acc.Expired_policies__c==null){
                                        acc.Expired_policies__c=0;
                                   }
                                    acc.Expired_policies__c+=1;
                                }    /*else if(csold.plan_status__c =='expired'&& cs.plan_status__c=='active')
                                {
                                    acc.Expired_policies__c-=1;
                                    acc.Active_policies__c+=1;
                                }*/
                                
                                //add the records to the collection
                                //lstaccount.add(acc);
                                
                            /*    
                            }
                        }updateaccount.put(acc.id,acc);
                    }
                    //update acctoupdate;
                    
                }///updateaccount.putall(lstaccount );
                system.debug('The map collection ...'+updateaccount );
                if(!updateaccount.isempty())
                    //update the map collection
                    update updateaccount.values();
                
            }
            
        }
    } */
hey guys,

In my org there is button called X(suppose it) i have to hide that button when status is active and unhide it when status is not active but the thing is button is a external url in community site so how i can complete this with the help of LWC(.js) without using html ..
 
  • July 05, 2023
  • Like
  • 0

I want the apex class  to return a list of Topics in experience cloud, I am getting error that variable does not exists: getNavigationTopics

 

Here is the code, and also can you please provide a test class for this? 

public with sharing class CustomAccordionLWC{
    @AuraEnabled(cacheable=true)
    public static List<ConnectApi.Topic> getNavigationTopics(){

        string commId = [Select Id from Network where Name = 'Payer Help Center'].Id;    
        ConnectApi.ManagedTopicCollection topics = ConnectApi.ManagedTopics.getManagedTopics(commId);
        for (ConnectApi.ManagedTopic managedTopic : topics.managedTopics) {
            System.debug('###managedTopic.topic.name = ' + ((ConnectApi.Topic)managedTopic.topic).name);
        
            Set<String> topicNames = new Set<String>();
            for (ConnectApi.ManagedTopic childManagedTopic : managedTopic.children) {
                topicNames.add(((ConnectApi.Topic)childManagedTopic.topic).name + '\n');
            }
        
            System.debug('### childTopicNames:\n' + String.join(topicNames, '\n'));
        }
			return getNavigationTopics; 
    }
            
}
 

 

Hello, 
I need to develop a trigger on this. Can anyone help me with that?

Develop a Trigger on Service-Consultant object which will throw an error if the Consultant Selected on
Service-Consultant Record already has an Service against his name. i.e - For a Consultant there will be only one Service at a time. Reject Duplicate Bookings.
Q1 - In which object the Trigger will be ( Service-Consultant) Q2 - What are the trigger events ( before insert, before update) Output - Check the duplicate bookings and throw the error.
Hi Team,

I have a zip file which I need to store to the static resource to have dependencies on my JS file. but My file size if 28 MB and static resource only takes 5 MB.
Is there any other way to save that ZIp file to static resource.

Regards
Nikhil
Hi ,
Trying to write the test class for the Opportunity Trigger and OpportunityTriggerHandler

Here is the Opportunity Trigger:

trigger OpportunityTrigger on Opportunity (after update) {
    
    if(Trigger.isAfter && Trigger.isUpdate){
        if(OpportunityTriggerHandler.isFirstTime){
            OpportunityTriggerHandler.isFirstTime=false;
            List<opportunity> opportunityList= new List<opportunity>();
            Map<id,decimal> optyProbabilityMap=new Map<id,decimal>();
            set<id> optyIds=new set<id>();
            for(opportunity opty:Trigger.new){
                if(opty.Probability != trigger.oldMap.get(opty.id).Probability){
                    opportunityList.add(opty);
                    optyIds.add(opty.Id);
                    if(!optyProbabilityMap.containsKey(opty.Id)){
                        optyProbabilityMap.put(opty.Id,opty.Probability);
                    }
                }
            }
            if(!opportunityList.isEmpty()){
                OpportunityTriggerHandler optyTrig=new OpportunityTriggerHandler();
                optyTrig.probabilityUpdate(opportunityList,optyIds,optyProbabilityMap);
            }
        }
    }
}


And here is the OpportunityTriggerHandler class:

public class OpportunityTriggerHandler {
    
    public static Boolean isFirstTime=true;
    
    
    public void probabilityUpdate(List<Opportunity> opportunityList,set<id> optyIds,Map<id,decimal> optyProbabilityMap){
        
        Map<id,OpportunityLineItem> optyProductMap= new Map<id,OpportunityLineItem>([SELECT id,name from OpportunityLineItem where OpportunityId IN :optyIds]);
        
        Map<Id, Opportunity> oppysMap = new Map<Id, Opportunity>([SELECT Id, Probability FROM Opportunity WHERE Id IN :optyIds]);
        
        List<OpportunityLineItemSchedule> optyLnItmSchedList=new List<OpportunityLineItemSchedule>();
        
        for(OpportunityLineItemSchedule eachLnItemSchdle : [SELECT id,Expected_Amount__c,Quantity,OpportunityLineItem.OpportunityId FROM 
                                                            OpportunityLineItemSchedule where OpportunityLineItemId IN: optyProductMap.keyset()]){
            
            Opportunity oppy = oppysMap.get(eachLnItemSchdle.OpportunityLineItem.OpportunityId);
            eachLnItemSchdle.Expected_Amount__c = eachLnItemSchdle.Quantity * (oppy.Probability / 100);                                                                
            optyLnItmSchedList.add(eachLnItemSchdle);                
        }
        
        update optyLnItmSchedList;
    }
}


And this is my Test Class:

@isTest
public class OpportunityTriggerHandlerTest {
    @isTest
    static void testProbabilityUpdate() {
        TestDataFactory factory = new TestDataFactory();

        // Create test Opportunity
        Opportunity opportunity = factory.createOpportunity('Test Opportunity', 'Prospecting', Date.today().addDays(30), 50);
        
        // Create test OpportunityLineItem
        OpportunityLineItem lineItem = factory.createOpportunityLineItem(opportunity, 2);
        
        // Create test OpportunityLineItemSchedule
        OpportunityLineItemSchedule schedule = factory.createOpportunityLineItemSchedule(lineItem, 2);

        // Invoke the method being tested
        OpportunityTriggerHandler handler = new OpportunityTriggerHandler();
        Set<Id> optyIds = new Set<Id>{opportunity.Id};
        Map<Id, Decimal> optyProbabilityMap = new Map<Id, Decimal>{opportunity.Id => opportunity.Probability};
        handler.probabilityUpdate(new List<Opportunity>{opportunity}, optyIds, optyProbabilityMap);
        
        // Retrieve the updated OpportunityLineItemSchedule record
        OpportunityLineItemSchedule updatedSchedule = [SELECT Expected_Amount__c FROM OpportunityLineItemSchedule WHERE Id = :schedule.Id];
        
        // Assert the expected values
        Decimal expectedAmount = schedule.Quantity * (opportunity.Probability / 100);
        System.assertEquals(expectedAmount, updatedSchedule.Expected_Amount__c);
    }
}

i get this dml error "System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: []"
How to solve this 

Thank you in advance
Pallavi
Query:-
 1. We can invoke only method with @WIRE Decorator.
  2. IMperative method invoke is not passible directly

I got the  information using chatGPT


you cannot directly invoke an Apex class from an Experience Site in a Lightning Web Component (LWC). Experience Sites are designed to provide a public-facing website experience for external users and do not have direct access to Apex code.
However, you can leverage Salesforce APIs to interact with your Apex code indirectly. You can create a custom Apex REST or SOAP web service that encapsulates the functionality you want to invoke. Then, from your LWC component hosted on the Experience Site, you can make HTTP requests to that custom web service to perform the desired actions.
Here's a general outline of the steps involved:
Create a custom Apex class that exposes the desired functionality as a REST or SOAP web service.
Configure the necessary access permissions for the custom web service to be accessible from the Experience Site's guest user profile.
In your LWC component, use the standard fetch() or XMLHttpRequest API to make an HTTP request to the custom web service endpoint.
Handle the response from the web service in your LWC component and update the UI accordingly.
By following this approach, you can indirectly invoke the functionality of your Apex class from the LWC component hosted on the Experience Site.

Kindly Help Here

 
CLASS:- 
  @RestResource(urlMapping='/Razorpay/*')
global class WebhooK_for_RazorPay 
{
    
@HttpPost
    global static void ResponseFromPaymentLInk()
    {
        
        
        RestRequest request = RestContext.request;
        system.debug('The request '+  request );
        RestResponse response = RestContext.response;
           system.debug('The response '+  response );
        
    }
     
}

Webhook URL:- https://techforceservices18-dev-ed.develop.my.site.com/services/apexrest/Razorpay

used in Razorpay 
How can we  show images in the Experience cloud site  which are having the URL in  the field of an Object using LWC component and it should using img tag  ?
 
can we create other methods in batch class of an apex apart from start , execute and finish methods?

Create two Objects say Obj1(Parent) and Obj2(Child) having similar fields. On creating record of Obj1, associated Obj2 record should be created and vice versa. Additionally, updates should also be in sync i.e. updating the parent should reflect in the child and vice versa.
 

How can I achieve this requirement.

Thanks in Advance!

  • October 28, 2020
  • Like
  • 0
Hi I am trying to Override CONVERT button on Lead with Lightning Web Component. But the issue is Override Properties is not Showing an option to Select a Lightning Component. I am adding screenshot for understanding my problem
User-added imagePlease do I need to change any settings or something, please suggest me a solution.

The following Error I'm getting------------>
===============================
Argument cannot be null.
Error is in expression '{!callme}' in component <apex:commandButton> in page vf_xml_eg1_xmldynamicaccount: Class.Eg1_XML_Dserfromfile.callme: line 7, column 1
An unexpected error has occurred. Your development organization has been notified.

The following CLASS used------------>
===============================
public class Eg1_XML_Dserfromfile 
{
    public Blob xmlfile {set;get;}
    public void callme()
    {
        list<Account> accounts = new list<Account>();
        String xmlstring = xmlfile.tostring();
        xmlfile=null;
        DOM.Document doc=new Dom.Document();
        doc.load(xmlstring);
        DOM.XmlNode root = doc.getRootElement();
        list<DOM.XmlNode> branch =root.getchildElements();
        for(DOM.XmlNode eb:branch)
        {
            Account A = New Account();
            A.Name = eb.getAttributeValue('Name');
            A.Name = eb.getAttributeValue('Mobile');
            A.Name = eb.getAttributeValue('CompanyType');
            accounts.add(A);
            }
        insert accounts;
    }
}

The following COMPONENT used in the Visualforce------------>
==============================================
<apex:page controller="Eg1_XML_Dserfromfile" >
    <apex:form>
        <apex:inputFile value="{!xmlfile}" fileName="dummyfile">
        </apex:inputFile>
        <apex:commandButton value="Click here to import" action="{!callme}"/>
    </apex:form>
</apex:page>

 

---------------------
Please, help me out.