• Coolday
  • NEWBIE
  • 80 Points
  • Member since 2022

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 20
    Questions
  • 25
    Replies
public class RestResource{
    
    public class SimpleRequest {
        public string email;
        public string password;
        public string storeKey;
    }
    public class SimpleResponse {
        public string jwtToken;
    }
    
    public static string getRequestSimple() {
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        SimpleRequest simpleReq = new SimpleRequest();
        my_Settings__c objset = my_Settings__c.getValues('custom');
        
        string endPoint = objset .End_Point__c;
        if(Test.isRunningTest()){
            simpleReq .email = 'XXXX@XXXX.com';
            simpleReq .password = 'XXXXXXX';
            simpleReq .storekey='msme';
        } else{
            simpleReq .email = objset.Username__c;
            simpleReq .password = objset.Password__c;
            simpleReq .storeKey = objset.Token__c;
        }
        req.setBody(JSON.serialize(simpleReq ));
        req.setMethod('POST');
        req.setEndpoint(endPoint);
        req.setHeader('Content-Type', 'application/json');
        HttpResponse hresp = h.send(req);
        SimpleResponse wResp = (SimpleResponse) JSON.deserialize(hresp.getBody(), SimpleResponse.class);
        system.debug('JWT ' + wResp.jwtToken);
        return wResp.jwtToken;
    }

    @future(callout=true)
    public static void sendRequestAsync(String payload,Id objectId, string customSettingName) {
        
        my_Log__c ilog = my_Log__c(); 
        ilog.Subject__c= customSettingName;
        ilog.Request__c=payload; 
        try{
            Http http                       =       new Http();
            HttpRequest request2            =       new HttpRequest();
            Map<String, Object> deserializedPayload = (Map<String, Object>)JSON.deserializeUntyped(payload);
            String type = (String)deserializedPayload.get('type');
            List<SObject> endpoint;
            my_Settings__c setting = my_Settings__c .getValues(customSettingName);  
            if(setting != null && setting.end_point__c != null){
                String username                 =       (String)setting.username__c; 
                String password                 =       (String)setting.password__c;
                String endp                     =       (String)setting.end_point__c;
                Blob headerValue                =       Blob.valueOf(username + ':' + password);
                String authorizationHeader      =       'Basic ' + EncodingUtil.base64Encode(headerValue);
                
                request2.setHeader      ('Authorization', authorizationHeader);
                request2.setHeader      ('APPKEY',(String)setting.app_key__c);
                request2.setEndpoint    (endp);
                request2.setMethod      ('POST');
                request2.setHeader      ('Content-Type', 'application/json; charset=utf-8');
                
                request2.setBody(payload);
                
                HttpResponse response = http.send(request2);
                
                system.debug('The Response Body: '+response.getBody());
                ilog.Response__c='response= '+response;
                ilog.Response_Status_Code__c='status Code= '+response.getStatusCode();  
                ilog.Response_Body__c=response.getBody();
                insert ilog;
                if(response.getStatusCode() != 200){
                    Myexception e = new Myxception();
                    e.setMessage(response.toString());
                    HandleCustomException.LogException(e,payload,null);
                } 
            }}catch(exception ex){
                ilog.Exception__c='Exception:: '+ex.getMessage()+' Line Number::'+ ex.getLineNumber();
                ilog.Response_Status_Code__c='ERROR';
                insert ilog;
            }
    }
    
    private class Myexception extends Exception{}
    
    
}

I have a requirement where I have to call my method (Invocable) inside Batch Execute() method.

Is it possible?

I have an existing Apex class which sends a payload to the third party whenever an Account is created on Salesforce side. 
I have a flow which triggers the apex class whenever an Account is created or updated.
 The new requirement is we need to write additional logic whenever an opportunity (associated with the account) is created then also send a different payload to the third party.  
 
Should I Modify my flow or make changes in the class?
 
 This is my Apex code -  

public class RESTAPI {
    @InvocableMethod()
    public static void sendRequest(List<Id> ids) {
        List <Account> objAcc = new List<Account>();
        
        objAcc = [Select Id,Name,Email__c,RecordType.Name from Account where 
                  Id in :ids];
       
        for(Account acc : objAcc) {
            ObjectWrapper objWrap = new ObjectWrapper ();
            objWrap.Id                         =           acc.Id;
            ObjectWrapper .cls_attributes attr               =           new ObjectWrapper .cls_attributes();
            attr.companyName                            =           acc.Name;
            attr.email                                  =           acc.Email__c;
            attr.sfRecordType                           =           acc.RecordType.Name;
            objWrap.attributes                          =           attr;
            
                    
            String payload          =           JSON.serialize(objWrap);
        
            if(!System.isFuture()) {
                sendRequestAsync(payload,acc.Id);
               
            }
		}
    }
    @future(callout=true)
    private static void sendRequestAsync(String payload,Id accId) {
        
        Http http                       =       new Http();
        HttpRequest request2            =       new HttpRequest();
        List<API__c> lstCS      =       API__c.getall().values();   
        if (lstCS != null && lstCS.size() > 0) {
            system.debug('102');
            String username                 =       lstCS[0].username__c;
            String password                 =       lstCS[0].password__c;
            String endp                     =       lstCS[0].endpoint__c;
            Blob headerValue                =       Blob.valueOf(username + ':' + password);
            String authorizationHeader      =       'Basic ' + EncodingUtil.base64Encode(headerValue);
            
            request2.setHeader      ('Authorization', authorizationHeader);
            request2.setEndpoint    (endp);
            request2.setMethod      ('POST');
            request2.setHeader      ('Content-Type', 'application/json; charset=utf-8');
            
            request2.setBody(payload);

            HttpResponse response = http.send(request2);
            system.debug('The Response Body: '+response.getBody());
        }         
    }
Is it possible to show dynamic button when number field is null using Lightning page 
User-added image
@RestResource(urlMapping='/v1/Order/*')
global class Order{
    global class Result {
        webservice Integer returnCode;
        webservice String message='';
        webservice String recordID;
        webservice String APIName='updateOrder';
    }
    
    
    @HttpPost
    global static Result UpdateOrder() {
        Result res=new Result();
        Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(RestContext.request.requestBody.toString());
        system.debug('jsonMap---'+jsonMap);
        List<Object> objectRecords = (List<Object>)jsonMap.get('orderDetails');
        Map<String, Object> recordValue = new  Map<String, Object>();
        
        Set<Id> orderIds = new Set<Id>();
        Map<String, Map<String, Object>> objectMap = new Map<String, Map<String,Object>>();
        for(Object o : objectRecords){
            Map<String, Object> rec = new  Map<String, Object>();
            rec = (Map<String, Object>)o;
            orderIds.add((string)rec.get('orderId'));
            objectMap.put((string)rec.get('orderId'), rec);
        } 
        List<Order> OrdersToBeUpdated = new List<Order>();
        
        List<Order> OrderList =[SELECT id,Order_Id__c,Payment_Amount__c, Payment_Status__c FROM Order where Order_Id__c In: orderIds];
        
        if(OrderList == null || OrderList.size() == 0){
            res.returnCode = 401;
            res.message = 'No Order found with this Order ID';
            return res;
        }
        
        if (!OrderList.isEmpty()) {
            for(order ordObj : OrderList){
                Map<String, Object> orderResMap = objectMap.get(ordObj.Order_Id__c);
                ordObj.Payment_Status__c = (String)orderResMap.get('paymentStatus');
                ordObj.Delivery_Status__c = (String)orderResMap.get('deliveryStatus');
                ordObj.Payment_Amount__c = (decimal)orderResMap.get('pendingAmount');
                ordObj.Paid_Amount__c = (decimal)orderResMap.get('paidAmount');
                OrdersToBeUpdated.add(ordObj);
                system.debug('recordValue---'+orderResMap.get('orderId'));
                system.debug('recordValue---'+orderResMap.get('orderNumber'));
                system.debug('recordValue---'+orderResMap.get('paymentStatus'));
                system.debug('recordValue---'+orderResMap.get('pendingAmount'));
            }
        }
        
        if(!OrdersToBeUpdated.isEmpty()){
            update OrdersToBeUpdated;
            res.returnCode = 200;
            res.message = 'Update successful';
            return res;
        }
        
        return null;
    }
    
}


I am getting this error when I am sending JSON from postman -

[
    {
        "errorCode": "APEX_ERROR",
        "message": "System.StringException: Invalid id: 1ba4a3e6-d592-4e4e-836c-4b00284b0d6f\n\nExternal entry point"
    }
]

We have to Create an attachment icon near the custom field.
Let me know if it is possible using salesforce standard functionality.
How to schedule my batch class for every 6 hours ?
This is my scheduler -
 
global class UpdateBatchSchedule implements Schedulable{
    global void execute(SchedulableContext ctx) {
        UpdateBatch p = new UpdateBatch();
        database.executeBatch(p,200);
    }  
}

 
I want to send a JSON to third party in Salesforce but there is a if condition.
How can I send it ?
Apex code -
objWrap.advancePayment = objOpp.Advance_Value__c;
            objWrap.self = objOpp.Self__c ;
            objWrap.isPKS = isPKS;
I have to only send isPKS if the advance__c is equal to 0.

How to achieve this?
We have a requirement where an email (Visualforce) is sent to the customer and they can either reply Accept or Reject and that response is captured in salesforce and based on that we are sending a reverse email using salesforce sites which has an Visualforce page for Accept and Reject response.
 
Currently we are facing an issue where a customer is able to accept or reject multiple times. So, to avoid that we want to show a message to the customer that "Your response is already captured".
 
How can this be achieved? 
Based on the Method in Apex controller can we conditionally show and hide our text in VF Page?
Code 
if(response.getStatusCode() != 200){
                exception e = new exception();
                e.setMessage(response.toString());
                HandleCustomException.LogException(e,payload,null);
            }

 
How can I include method name in this below line in Visualforce- 

<button class="accept-btn" type="button">Accept</button>

Thanks
Apex class 

@RestResource(urlMapping='/v1/Task/*')
global class TaskCreation {
    global class Result {
        webservice Integer returnCode;
        webservice String message='';
    }
     @HttpPost
     global static Result CreationLeadTask() {
        Result res=new Result();
        Map<String, Object> requestBody = (Map<String, Object>)JSON.deserializeUntyped(RestContext.request.requestBody.toString());
        Map < String, Object > mSet = (Map < String, Object > ) requestBody.get('taskDetails');
        String ID = (String) mSet.get('cusID'); 
        String assignedTo = (String) mSet.get('assignedTo');
        String taskName = (String) mSet.get('taskName');
        String priority = (String) mSet.get('priority');
        String activityDate = (String) mSet.get('activityDate');
        Date newDate = activityDate != '' && activityDate != null ? Date.valueOf(activityDate) : null;
         
        List<Lead> LeadsToBeUpdated = new List<Lead>();
        if (String.isEmpty(ID)) {
            res.returnCode = 400;
            res.message='Required';
            return res;
        } 
            List<Lead> Leadlist =[SELECT id,Lead.OwnerId, RecordType.DeveloperName FROM Lead where Id = :ID AND RecordType.DeveloperName = 'Person'];
            if(Leadlist == null || Leadlist.size() == 0){
                res.returnCode = 401;
                res.message = 'No Lead found with this Id';
                return res;
            }
                List<Task> Tasklist = new List<Task>();
                Task Ta = new Task();
                Ta.OwnerId= assignedTo != '' && assignedTo != null ? assignedTo : Leadlist[0].OwnerId;
                Ta.Status = 'New';
                Ta.Subject= taskName;
                Ta.Priority = priority != '' && priority != null ? priority : 'Normal';
                Ta.WhoId = Leadlist[0].id;
                Ta.ActivityDate =newDate;
                Tasklist.add(Ta);
    
        if (!Tasklist.isEmpty()) {
            insert Tasklist ;
            res.returnCode = 201;
            res.recordId = Tasklist[0].id;
            res.message='Task creation was successful.';
        }
        if (Leadlist.size() != 0 && Ta.Subject == 'TASK CREATION') {
            System.debug('123');
                Lead LeadUpdate = new Lead(Id = Leadlist[0].Id); 
                LeadUpdate.update = 'Yes';
                LeadUpdate.add(LeadUpdate);
        }
        Update LeadUpdate;
        return res;
    }
}
I want to change the Date Time format of below line to YYYY-MM-DDT00:00:00Z

att.Time = acc.Time__c != null ? String.valueof(acc.Time__c ) : null;

Thanks and Regards

 
  • September 28, 2022
  • Like
  • 0
I am getting the below error when I am doing bulk update.
List has more than 1 row for assignment to SObject

on this line of my code - 
Account acc = [SELECT Email__c FROM Account WHERE Id IN (SELECT AccountId from Opportunity WHERE Id =:Ids)];

My Apex class -

@InvocableMethod
    public static void calculate(List<Id> Ids){
        System.debug('--Id : '+Ids);
            if(!System.isFuture()) {
                CallculateCalloutAsync(Ids);
        }
    } 
    @future(callout=true)
    public static void CallculateCalloutAsync(List<Id> Ids){
        Account acc = [SELECT Email__c FROM Account WHERE Id IN (SELECT AccountId from Opportunity WHERE Id =:Ids)];
        HTTP http = new HTTP();
        HTTPRequest request = new HTTPRequest();
        List<Amount__c> listCS      =       Amount__c.getall().values();   
        if (listCS != null && listCS.size() > 0) {
            String endp                     =       listCS[0].endpoint__c+acc.Email__c;
            String auth                     =       listCS[0].auth__c;
            String authorizationHeader      =       'Basic '+ auth;
            
            request.setHeader      ('Authorization', authorizationHeader);
            request.setEndpoint    (endp);
            request.setMethod      ('GET');
            request.setHeader      ('Content-Type', 'application/json; charset=utf-8');
            HTTPResponse response = http.send(request);
            system.debug('--response : '+response.getBody());
            
            if(response.getStatusCode() == 200){
                system.debug('The Response Body: '+response.getBody());
                Map<String, Object> deserializedPayload = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
                Decimal balance = (Decimal)deserializedPayload.get('tax');
                Opportunity opp = new Opportunity(Id = Ids[0]);
                opp.amount__c = tax;
                update opp;
            } 
            if(response.getStatusCode() != 200){
                System.debug('The Response Body: '+response.getBody());
                System.debug('No data found!');
            }
 
  • September 26, 2022
  • Like
  • 0
We have a requirement where based on checkbox field different logic should run.

if(fieldname == false || fieldname == true){
//logic
}
else if (fieldname == true){
//logic
}

The issue is only the first condition gets executed.
How can this be resolved.
  • September 23, 2022
  • Like
  • 0
Can anyone tell me why I am getting this error in my code - 
Illegal assignment from List<Id> to Id -(on this line)
Opportunity opp = new Opportunity(Id = Ids);

Apex class -

    @InvocableMethod
    public static void amount(List<Id> Ids){
        Account acc = [SELECT Email__c FROM Account WHERE Id IN (SELECT AccountId from Opportunity WHERE Id =:Ids)];
        HTTP http = new HTTP();
        HTTPRequest request = new HTTPRequest();
        List<Amount__c> listCS      =       Amount__c.getall().values();   
        if (listCS != null && listCS.size() > 0) {
            String endp                     =       listCS[0].endpoint__c+acc.Email__c;
            String auth                     =       listCS[0].auth__c;
            String authorizationHeader      =       'Basic '+ auth; 
            
            request.setHeader      ('Authorization', authorizationHeader);
            request.setEndpoint    (endp);
            request.setMethod      ('GET');
            request.setHeader      ('Content-Type', 'application/json; charset=utf-8');
            HTTPResponse response = http.send(request);
        
        if(response.getStatusCode() == 200){
            system.debug('The Response Body: '+response.getBody());
            Map<String, Object> deserializedPayload = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
            Decimal tax = (Decimal)deserializedPayload.get('tax');
            Opportunity opp = new Opportunity(Id = Ids);
            opp.tax__c = tax;
            update opp;
        }  }  }
  • September 21, 2022
  • Like
  • 0
We have a requirement for which I created a LWC component and Flow for the same Apex class. Can we use @Auraenabled and @Invokable at the same time for the method in Apex class.

Thanks 
  • September 21, 2022
  • Like
  • 0
Using a Record Triggered flow can we update a field on click of a Quick Action button ?
If Not , Then how is it possibile?
  • September 19, 2022
  • Like
  • 0

I have a requirement where I have to create a validation rule - There is an object opportunity (Master) and  a custom object (Detail). Whenever stage is Qualification on opportunity then I have to lock 3 fields from editing  Field 1 , Field 2 and Field 3. Field 1 is on opportunity object and Field 2 and 3 are on custom object. 

I created the validation rule on custom object -

AND( ISPICKVAL(ISPRIORVAL( Opportunity__r.StageName) , 'Qualification') ,
 OR(
ISCHANGED( Opportunity__r.Field1 )
 ISCHANGED( Field2 ) ,
  ISCHANGED( Field3 ),
 )
)
I am getting this error -
The PRIORVALUE function cannot reference the field (ISPRIORVAL( Opportunity__r.StageName) validation rule.

Also, We do not have any lookup on opportunity to custom object so I had to create the validation rule on Custom Object.

  • September 19, 2022
  • Like
  • 0
I want to send a JSON to third party in Salesforce but there is a if condition.
How can I send it ?
Apex code -
objWrap.advancePayment = objOpp.Advance_Value__c;
            objWrap.self = objOpp.Self__c ;
            objWrap.isPKS = isPKS;
I have to only send isPKS if the advance__c is equal to 0.

How to achieve this?

I have an existing Apex class which sends a payload to the third party whenever an Account is created on Salesforce side. 
I have a flow which triggers the apex class whenever an Account is created or updated.
 The new requirement is we need to write additional logic whenever an opportunity (associated with the account) is created then also send a different payload to the third party.  
 
Should I Modify my flow or make changes in the class?
 
 This is my Apex code -  

public class RESTAPI {
    @InvocableMethod()
    public static void sendRequest(List<Id> ids) {
        List <Account> objAcc = new List<Account>();
        
        objAcc = [Select Id,Name,Email__c,RecordType.Name from Account where 
                  Id in :ids];
       
        for(Account acc : objAcc) {
            ObjectWrapper objWrap = new ObjectWrapper ();
            objWrap.Id                         =           acc.Id;
            ObjectWrapper .cls_attributes attr               =           new ObjectWrapper .cls_attributes();
            attr.companyName                            =           acc.Name;
            attr.email                                  =           acc.Email__c;
            attr.sfRecordType                           =           acc.RecordType.Name;
            objWrap.attributes                          =           attr;
            
                    
            String payload          =           JSON.serialize(objWrap);
        
            if(!System.isFuture()) {
                sendRequestAsync(payload,acc.Id);
               
            }
		}
    }
    @future(callout=true)
    private static void sendRequestAsync(String payload,Id accId) {
        
        Http http                       =       new Http();
        HttpRequest request2            =       new HttpRequest();
        List<API__c> lstCS      =       API__c.getall().values();   
        if (lstCS != null && lstCS.size() > 0) {
            system.debug('102');
            String username                 =       lstCS[0].username__c;
            String password                 =       lstCS[0].password__c;
            String endp                     =       lstCS[0].endpoint__c;
            Blob headerValue                =       Blob.valueOf(username + ':' + password);
            String authorizationHeader      =       'Basic ' + EncodingUtil.base64Encode(headerValue);
            
            request2.setHeader      ('Authorization', authorizationHeader);
            request2.setEndpoint    (endp);
            request2.setMethod      ('POST');
            request2.setHeader      ('Content-Type', 'application/json; charset=utf-8');
            
            request2.setBody(payload);

            HttpResponse response = http.send(request2);
            system.debug('The Response Body: '+response.getBody());
        }         
    }
Is it possible to show dynamic button when number field is null using Lightning page 
User-added image
We have to Create an attachment icon near the custom field.
Let me know if it is possible using salesforce standard functionality.
How to schedule my batch class for every 6 hours ?
This is my scheduler -
 
global class UpdateBatchSchedule implements Schedulable{
    global void execute(SchedulableContext ctx) {
        UpdateBatch p = new UpdateBatch();
        database.executeBatch(p,200);
    }  
}

 
Apex class 

@RestResource(urlMapping='/v1/Task/*')
global class TaskCreation {
    global class Result {
        webservice Integer returnCode;
        webservice String message='';
    }
     @HttpPost
     global static Result CreationLeadTask() {
        Result res=new Result();
        Map<String, Object> requestBody = (Map<String, Object>)JSON.deserializeUntyped(RestContext.request.requestBody.toString());
        Map < String, Object > mSet = (Map < String, Object > ) requestBody.get('taskDetails');
        String ID = (String) mSet.get('cusID'); 
        String assignedTo = (String) mSet.get('assignedTo');
        String taskName = (String) mSet.get('taskName');
        String priority = (String) mSet.get('priority');
        String activityDate = (String) mSet.get('activityDate');
        Date newDate = activityDate != '' && activityDate != null ? Date.valueOf(activityDate) : null;
         
        List<Lead> LeadsToBeUpdated = new List<Lead>();
        if (String.isEmpty(ID)) {
            res.returnCode = 400;
            res.message='Required';
            return res;
        } 
            List<Lead> Leadlist =[SELECT id,Lead.OwnerId, RecordType.DeveloperName FROM Lead where Id = :ID AND RecordType.DeveloperName = 'Person'];
            if(Leadlist == null || Leadlist.size() == 0){
                res.returnCode = 401;
                res.message = 'No Lead found with this Id';
                return res;
            }
                List<Task> Tasklist = new List<Task>();
                Task Ta = new Task();
                Ta.OwnerId= assignedTo != '' && assignedTo != null ? assignedTo : Leadlist[0].OwnerId;
                Ta.Status = 'New';
                Ta.Subject= taskName;
                Ta.Priority = priority != '' && priority != null ? priority : 'Normal';
                Ta.WhoId = Leadlist[0].id;
                Ta.ActivityDate =newDate;
                Tasklist.add(Ta);
    
        if (!Tasklist.isEmpty()) {
            insert Tasklist ;
            res.returnCode = 201;
            res.recordId = Tasklist[0].id;
            res.message='Task creation was successful.';
        }
        if (Leadlist.size() != 0 && Ta.Subject == 'TASK CREATION') {
            System.debug('123');
                Lead LeadUpdate = new Lead(Id = Leadlist[0].Id); 
                LeadUpdate.update = 'Yes';
                LeadUpdate.add(LeadUpdate);
        }
        Update LeadUpdate;
        return res;
    }
}
I want to change the Date Time format of below line to YYYY-MM-DDT00:00:00Z

att.Time = acc.Time__c != null ? String.valueof(acc.Time__c ) : null;

Thanks and Regards

 
  • September 28, 2022
  • Like
  • 0
We have a requirement where based on checkbox field different logic should run.

if(fieldname == false || fieldname == true){
//logic
}
else if (fieldname == true){
//logic
}

The issue is only the first condition gets executed.
How can this be resolved.
  • September 23, 2022
  • Like
  • 0
Can anyone tell me why I am getting this error in my code - 
Illegal assignment from List<Id> to Id -(on this line)
Opportunity opp = new Opportunity(Id = Ids);

Apex class -

    @InvocableMethod
    public static void amount(List<Id> Ids){
        Account acc = [SELECT Email__c FROM Account WHERE Id IN (SELECT AccountId from Opportunity WHERE Id =:Ids)];
        HTTP http = new HTTP();
        HTTPRequest request = new HTTPRequest();
        List<Amount__c> listCS      =       Amount__c.getall().values();   
        if (listCS != null && listCS.size() > 0) {
            String endp                     =       listCS[0].endpoint__c+acc.Email__c;
            String auth                     =       listCS[0].auth__c;
            String authorizationHeader      =       'Basic '+ auth; 
            
            request.setHeader      ('Authorization', authorizationHeader);
            request.setEndpoint    (endp);
            request.setMethod      ('GET');
            request.setHeader      ('Content-Type', 'application/json; charset=utf-8');
            HTTPResponse response = http.send(request);
        
        if(response.getStatusCode() == 200){
            system.debug('The Response Body: '+response.getBody());
            Map<String, Object> deserializedPayload = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
            Decimal tax = (Decimal)deserializedPayload.get('tax');
            Opportunity opp = new Opportunity(Id = Ids);
            opp.tax__c = tax;
            update opp;
        }  }  }
  • September 21, 2022
  • Like
  • 0