• K Roy
  • NEWBIE
  • 30 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 17
    Questions
  • 11
    Replies
I have a requirement where i have to reprocess the failed records in batch apex. Please help me with the process.
  • May 02, 2023
  • Like
  • 0
-----------------------
Class
-----------------------
@RestResource(urlMapping='/leadconvert/*')
global with sharing class RestLeadConvert {
    public static final Integer StatusCodeOK = 200;
    public static final Integer StatusCodeBadRequest = 400;
    public static final Integer StatusCodeInternalServerError = 500;
    public static String DEFAULT_CONVERTED_STATUS = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true limit 1].MasterLabel;

    public class BadRequestException extends Exception {}

    // Represents a REST response
    class ResponseObject {
        String message;
        String code;
        Database.LeadConvertResult lead_convert_result;

        public Blob blob() {
            return Blob.valueOf(JSON.serialize(this));
        }

        public ResponseObject(String message, String code, Database.LeadConvertResult lcr) {
            this(message, code);
            this.lead_convert_result = lcr;
        }

        public ResponseObject(String message, String code) {
            this.message = message;
            this.code = code;
        }
    }

    @HttpPost
    global static void doPost() {
        RestContext.response.addHeader('Content-Type', 'application/json');

        Database.LeadConvertResult lcr ;
        try {
            Database.LeadConvert lc = parseRequest(RestContext.request);
            lc.setLeadId(parseTrailingLeadId(RestContext.request.requestURI));

            lcr = Database.convertLead(lc);
        }
        catch (Exception e) {
            RestContext.response.responseBody = new ResponseObject(e.getMessage(), exceptionTypeNameToCode(e)).blob();

            if (e.getTypeName() == 'RestLeadConvert.BadRequestException') {
                RestContext.response.statusCode = StatusCodeBadRequest;
            }
            else {
                // any other exception is unexpected; dump the exception and a stack trace to help debug it in production
                system.debug(e);
                system.debug(e.getStackTraceString());
                RestContext.response.statusCode = StatusCodeInternalServerError;
            }
            return;
        }
    
        if (lcr.isSuccess()) {
            RestContext.response.responseBody = new ResponseObject('Success', 'success', lcr).blob();
            RestContext.response.statusCode = StatusCodeOK;
        }
        else {
            RestContext.response.responseBody = new ResponseObject('Fail', 'see lead_convert_result', lcr).blob();
            RestContext.response.statusCode = StatusCodeInternalServerError;
        }
    }

    // Given an Exception typename like 'RestLeadConvert.BadRequestException', return 'BadRequestException'
    static String exceptionTypeNameToCode(Exception e) {
        String[] qualifiedName = e.getTypeName().split('\\.');
        return qualifiedName[qualifiedName.size()-1];
    }
    
    // completely parse the request body into an instance of LeadConvertBody
    // throw exception if it fails to parse in any way
    @TestVisible static Database.LeadConvert parseRequest(RestRequest request) {
        if (request.requestBody == null) {
            return createDefaultLeadConvert();
        }

        try {
            return (Database.LeadConvert)JSON.deserialize(request.requestBody.toString(), Database.LeadConvert.class);
        }
        catch(Exception e) {
            throw new BadRequestException('Failed to deserialize json body (%)'.replace('%', e.getMessage()));
        }
    }

    // this determines the behavior for a POST with no request body
    static Database.LeadConvert createDefaultLeadConvert() {
        Database.LeadConvert lc = new Database.LeadConvert(); 
        lc.setConvertedStatus(DEFAULT_CONVERTED_STATUS);
        return lc;
    }

    // get the LeadId from the requestURI and throw an exception if impossible
    static Id parseTrailingLeadId(String requestURI) {
        String leadId = getTrailingLeadId(requestURI);
        if (leadId == null) {
            throw new BadRequestException('requestURI does not have a valid trailing Lead Id');
        }
        return leadId;
    }

    // get the LeadId from the requestURI and return null if impossible
    @TestVisible
    static Id getTrailingLeadId(String requestURI) {
        Integer lastSlashIndex = requestURI.lastIndexOf('/');
        if (lastSlashIndex != -1) {
            String leadId = requestURI.substring(lastSlashIndex+1);
            if (leadId instanceOf Id && ((ID)leadId).getsobjecttype() == Schema.Lead.getSObjectType()) {
                return (Id)leadId;
            }
        }

        return null;
    }
}

-----------------------------------
Test Class
-----------------------------------
@isTest
public class RestLeadConvertTest{
    @isTest static void testDoPost()
    {
        Lead lead = new Lead (FirstName = 'John', LastName = 'Test', Company = 'Test Company' , Email = 'johntest@xyz.com');
        insert lead;
        
        RestRequest req = new RestRequest();
        req.addHeader('Content-Type', 'application/json');
        req.requestURI = '/services/apexrest/leadconvert/' + lead.Id;
        req.httpMethod = 'POST';
        RestContext.request = req;
        
        RestLeadConvert.doPost();
        System.assertEquals(RestLeadConvert.StatusCodeOK, RestContext.response.statusCode,'The Response is 200');
        
        
        RestRequest req2 = new RestRequest();
        req2.addHeader('Content-Type', 'application/json');
        req2.requestURI = '/services/apexrest/leadconvert/invalidLeadId';
        req2.httpMethod = 'POST';
        RestContext.request = req2;
        
        RestLeadConvert.doPost();
        System.assertEquals(RestLeadConvert.StatusCodeBadRequest, RestContext.response.statusCode,'The Response is 400');
        
        
    }
}
  • March 21, 2023
  • Like
  • 0
I have a requirment where, i need to call a button automatically based on a field value in the opportunity object. The button is present in a lightning page.
  • January 20, 2023
  • Like
  • 0
Hi Team,

I am two apex classes.

In Apex CLASS A:

public class A {
public String otID {get;set;}

public A()
{
otID = B.getotMethod();

}

In Apex CLASS B:

I have written a method:

@AuraEnabled
public string getotMethod()
{
//////
return value;
}

I am getting an error in class A while saving. Please help me on this.

 
  • April 07, 2022
  • Like
  • 0
Hi team,
 
I am working on a screen flow, where i am saving a few data. Now i want to drop an email to a group of users based on their profile, directly from the flow itself. I have made this possible, using a workflow, but i want to do it from the screen flow itself. Can anyone help me as to how to do it?

User-added image
  • March 16, 2022
  • Like
  • 0
Hello,

I am trying to fetch the cookies which has been set from a page before. I want access it, which is getting stored in browser. My page is written in Aura, hence, 
Map<String, System.Cookie> cookieMap = ApexPages.currentPage().getCookies();

Is not working in the apex class. Can anyone help me how to get the cookies from the browser?
  • February 23, 2022
  • Like
  • 0
Hello Everyone,

I have an object, which has got a sharing rule written on it. It is being shared with a specific role. Does that mean, only the users in that specific role will see that record? and no one else?
 
Please help me understand this scenario.

Thanks in advance
  • August 12, 2020
  • Like
  • 0
Hello Team,

How Can I update a case field from a force.com site user with guest license through a controller?

 
  • January 08, 2020
  • Like
  • 0
Hi Team,

i have a visualforce page, where i am populating a picklist from an object "A". Now when a picklist value is chosen, i would like to save the value immidiately in a custom field in the "Case" object. How can i achieve this?
 
  • December 10, 2019
  • Like
  • 0
Hello All,

I have an email template, which is triggered when responses are captured. Based on the responses that are captured, a "single merge field" changes. Rest of the body of the email remains the same. Hence, presently for every response that is captured, a new mail gets triggered.
for example: if the Response is 1: Hi thank you for the "1" mail.
What i want to do is, Depending on the Responses captured, i just want to trigger only one email. Like if the reponse is 1, 2,3,4, then only one email will be triggered saying "Hi thank you for the "1,2,3,4" mail".

Can i get some help in this?

Thanks in advance. 
  • May 27, 2019
  • Like
  • 0
Hello,

I am getting the following error in the above trailhead mentioned.
"The 'Dreamhouse Classic App' doesn't appear to be visible in Lightning Experience."

i have given the required permissions, still i am getting this. Please find the screenshot, of the permissions.

Lightning Enabled
  • April 09, 2019
  • Like
  • 0
Hello Team,

I need a formula in a process builder which should break a given text into various parts and hence display me the result.
E.G: i am supplying the string as "GB;IT;"
I need the result only as GB.

Thanks in Advance.
  • March 29, 2019
  • Like
  • 0
Hello Team, 

I am facing an issue while writing the formula inside the process builder.
I have used a custom settings, where i have got 6 custom fields and all of which are text types.
Now, while defining the criteria in the process builder, i want to first check if the fields are blank or not and then proceed to the next step, i.e the action, where i need to concat only the available fields, based on the country code. for E.g, Account_Identifier_City__c contains GB;IT;FR; in this manner in the custom setting, and the country code mentioned there gets to see the city value, which i need to print in a single text field by concatenating.

For the first step, what i have done is:
=================================================
ISBLANK($Setup.Account_Identifier_Value__c.Account_Identifier_Address_Line__c) || 
ISBLANK($Setup.Account_Identifier_Value__c.Account_Identifier_City__c) || ISBLANK($Setup.Account_Identifier_Value__c.Account_Identifier_Postal_Code__c) || 
ISBLANK($Setup.Account_Identifier_Value__c.Account_Identifier_ABC_ID__c) || 
ISBLANK($Setup.Account_Identifier_Value__c.Account_Identifier_SAP_ID__c) || 
ISBLANK($Setup.Account_Identifier_Value__c.Account_Identifier_Status__c )
================================================
for the immediate actions, i am unable to figure out how to proceed. 
Can anyone help me in both these steps?
  • March 29, 2019
  • Like
  • 0
Hello All,
I have a situation where i need to populate a few values in a text field. Now since it will be country specific, i need to create hierarchy based custom settings and then have to use it from a process builder to update the corresponding text field. How can i achieve this?

Thanks in advance.
  • March 27, 2019
  • Like
  • 0
Hello Team,

I have recently started working in lightning. I am trying to work on a scenario, where i will be displaying the Account name in a dropdown. On selecting an Account, it will show the corresponding Contacts associated with the account. To achieve this, i am using lightning:Combobox.

My Component:
 
<aura:component implements="flexipage:availableForAllPageTypes" access="global" controller ="AccountDropDownListController">
    <aura:attribute name="accounts" type ="Account[]"/>
    <aura:handler name = "init" value="{!this}" action="{!c.init}" />
    <lightning:combobox name="general" label="Account List" placeholder="Select an Account" options="{! v.accounts }" onchange="{! c.handleChange }"/>
</aura:component>

Apex Controller:

public class AccountDropDownListController {
    @AuraEnabled
      public static List <String> getAccounts() 
      {
          List<Account> lstAccount= [SELECT Id, name, industry, Type, NumberOfEmployees, TickerSymbol, Phone FROM Account ORDER BY createdDate ASC];
          List<String> lstStrngAccount = new List<String>();
          for(Account acc:lstAccount)
          {
            lstStrngAccount.add(acc.Name);  
          }
          return lstStrngAccount;
      }
    }

Client Side Controller:

({
    init: function (component, event, helper) {
        helper.getAccountList(component);
    },
    handleChange: function (component, event,helper) {
        // This will contain the string of the "value" attribute of the selected option
        var selectedAccountValue = event.getParam("value");
        alert("Account selected with value: '" + selectedAccountValue + "'");
    }
})

Helper:

({
      getAccountList: function(component) {
    var action = component.get('c.getAccounts');
    var self = this;
    action.setCallback(this, function(actionResult) {
    component.set('v.accounts', actionResult.getReturnValue());
    var k = actionResult.getReturnValue();
    var items = [];
        for (var i = 0; i < k.length; i++) {
            var item = {
                "label": k[i] + " Option",
                "value": k[i].toString(),
            };
            items.push(item);
        }
        component.set("v.accounts", items);
   });
    $A.enqueueAction(action);
  }
})

What i am unable to do is, i am not able to click the Accounts, that i am selecting. How can i do that? Also after clicking, how can i get the corresponding contacts associated with those accounts?

Request you all to kindly guide me on this.

Regards,
Rahul
  • February 13, 2019
  • Like
  • 0
Hello I am learning apex and i am very new with it. I was working on a trigger, and i have got this piece of code. However, i am getting an error. 
Please find the code below.

Contact test1 = new Contact(Last Name='Allergan Verma');
insert test1;

The error is "Unexpected token: test1". Can anyone guide me through this?
  • March 26, 2018
  • Like
  • 0
-----------------------
Class
-----------------------
@RestResource(urlMapping='/leadconvert/*')
global with sharing class RestLeadConvert {
    public static final Integer StatusCodeOK = 200;
    public static final Integer StatusCodeBadRequest = 400;
    public static final Integer StatusCodeInternalServerError = 500;
    public static String DEFAULT_CONVERTED_STATUS = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true limit 1].MasterLabel;

    public class BadRequestException extends Exception {}

    // Represents a REST response
    class ResponseObject {
        String message;
        String code;
        Database.LeadConvertResult lead_convert_result;

        public Blob blob() {
            return Blob.valueOf(JSON.serialize(this));
        }

        public ResponseObject(String message, String code, Database.LeadConvertResult lcr) {
            this(message, code);
            this.lead_convert_result = lcr;
        }

        public ResponseObject(String message, String code) {
            this.message = message;
            this.code = code;
        }
    }

    @HttpPost
    global static void doPost() {
        RestContext.response.addHeader('Content-Type', 'application/json');

        Database.LeadConvertResult lcr ;
        try {
            Database.LeadConvert lc = parseRequest(RestContext.request);
            lc.setLeadId(parseTrailingLeadId(RestContext.request.requestURI));

            lcr = Database.convertLead(lc);
        }
        catch (Exception e) {
            RestContext.response.responseBody = new ResponseObject(e.getMessage(), exceptionTypeNameToCode(e)).blob();

            if (e.getTypeName() == 'RestLeadConvert.BadRequestException') {
                RestContext.response.statusCode = StatusCodeBadRequest;
            }
            else {
                // any other exception is unexpected; dump the exception and a stack trace to help debug it in production
                system.debug(e);
                system.debug(e.getStackTraceString());
                RestContext.response.statusCode = StatusCodeInternalServerError;
            }
            return;
        }
    
        if (lcr.isSuccess()) {
            RestContext.response.responseBody = new ResponseObject('Success', 'success', lcr).blob();
            RestContext.response.statusCode = StatusCodeOK;
        }
        else {
            RestContext.response.responseBody = new ResponseObject('Fail', 'see lead_convert_result', lcr).blob();
            RestContext.response.statusCode = StatusCodeInternalServerError;
        }
    }

    // Given an Exception typename like 'RestLeadConvert.BadRequestException', return 'BadRequestException'
    static String exceptionTypeNameToCode(Exception e) {
        String[] qualifiedName = e.getTypeName().split('\\.');
        return qualifiedName[qualifiedName.size()-1];
    }
    
    // completely parse the request body into an instance of LeadConvertBody
    // throw exception if it fails to parse in any way
    @TestVisible static Database.LeadConvert parseRequest(RestRequest request) {
        if (request.requestBody == null) {
            return createDefaultLeadConvert();
        }

        try {
            return (Database.LeadConvert)JSON.deserialize(request.requestBody.toString(), Database.LeadConvert.class);
        }
        catch(Exception e) {
            throw new BadRequestException('Failed to deserialize json body (%)'.replace('%', e.getMessage()));
        }
    }

    // this determines the behavior for a POST with no request body
    static Database.LeadConvert createDefaultLeadConvert() {
        Database.LeadConvert lc = new Database.LeadConvert(); 
        lc.setConvertedStatus(DEFAULT_CONVERTED_STATUS);
        return lc;
    }

    // get the LeadId from the requestURI and throw an exception if impossible
    static Id parseTrailingLeadId(String requestURI) {
        String leadId = getTrailingLeadId(requestURI);
        if (leadId == null) {
            throw new BadRequestException('requestURI does not have a valid trailing Lead Id');
        }
        return leadId;
    }

    // get the LeadId from the requestURI and return null if impossible
    @TestVisible
    static Id getTrailingLeadId(String requestURI) {
        Integer lastSlashIndex = requestURI.lastIndexOf('/');
        if (lastSlashIndex != -1) {
            String leadId = requestURI.substring(lastSlashIndex+1);
            if (leadId instanceOf Id && ((ID)leadId).getsobjecttype() == Schema.Lead.getSObjectType()) {
                return (Id)leadId;
            }
        }

        return null;
    }
}

-----------------------------------
Test Class
-----------------------------------
@isTest
public class RestLeadConvertTest{
    @isTest static void testDoPost()
    {
        Lead lead = new Lead (FirstName = 'John', LastName = 'Test', Company = 'Test Company' , Email = 'johntest@xyz.com');
        insert lead;
        
        RestRequest req = new RestRequest();
        req.addHeader('Content-Type', 'application/json');
        req.requestURI = '/services/apexrest/leadconvert/' + lead.Id;
        req.httpMethod = 'POST';
        RestContext.request = req;
        
        RestLeadConvert.doPost();
        System.assertEquals(RestLeadConvert.StatusCodeOK, RestContext.response.statusCode,'The Response is 200');
        
        
        RestRequest req2 = new RestRequest();
        req2.addHeader('Content-Type', 'application/json');
        req2.requestURI = '/services/apexrest/leadconvert/invalidLeadId';
        req2.httpMethod = 'POST';
        RestContext.request = req2;
        
        RestLeadConvert.doPost();
        System.assertEquals(RestLeadConvert.StatusCodeBadRequest, RestContext.response.statusCode,'The Response is 400');
        
        
    }
}
  • March 21, 2023
  • Like
  • 0
I have a requirment where, i need to call a button automatically based on a field value in the opportunity object. The button is present in a lightning page.
  • January 20, 2023
  • Like
  • 0
Hi team,
 
I am working on a screen flow, where i am saving a few data. Now i want to drop an email to a group of users based on their profile, directly from the flow itself. I have made this possible, using a workflow, but i want to do it from the screen flow itself. Can anyone help me as to how to do it?

User-added image
  • March 16, 2022
  • Like
  • 0
Hello Team,

I need a formula in a process builder which should break a given text into various parts and hence display me the result.
E.G: i am supplying the string as "GB;IT;"
I need the result only as GB.

Thanks in Advance.
  • March 29, 2019
  • Like
  • 0
Hello Team,

I have recently started working in lightning. I am trying to work on a scenario, where i will be displaying the Account name in a dropdown. On selecting an Account, it will show the corresponding Contacts associated with the account. To achieve this, i am using lightning:Combobox.

My Component:
 
<aura:component implements="flexipage:availableForAllPageTypes" access="global" controller ="AccountDropDownListController">
    <aura:attribute name="accounts" type ="Account[]"/>
    <aura:handler name = "init" value="{!this}" action="{!c.init}" />
    <lightning:combobox name="general" label="Account List" placeholder="Select an Account" options="{! v.accounts }" onchange="{! c.handleChange }"/>
</aura:component>

Apex Controller:

public class AccountDropDownListController {
    @AuraEnabled
      public static List <String> getAccounts() 
      {
          List<Account> lstAccount= [SELECT Id, name, industry, Type, NumberOfEmployees, TickerSymbol, Phone FROM Account ORDER BY createdDate ASC];
          List<String> lstStrngAccount = new List<String>();
          for(Account acc:lstAccount)
          {
            lstStrngAccount.add(acc.Name);  
          }
          return lstStrngAccount;
      }
    }

Client Side Controller:

({
    init: function (component, event, helper) {
        helper.getAccountList(component);
    },
    handleChange: function (component, event,helper) {
        // This will contain the string of the "value" attribute of the selected option
        var selectedAccountValue = event.getParam("value");
        alert("Account selected with value: '" + selectedAccountValue + "'");
    }
})

Helper:

({
      getAccountList: function(component) {
    var action = component.get('c.getAccounts');
    var self = this;
    action.setCallback(this, function(actionResult) {
    component.set('v.accounts', actionResult.getReturnValue());
    var k = actionResult.getReturnValue();
    var items = [];
        for (var i = 0; i < k.length; i++) {
            var item = {
                "label": k[i] + " Option",
                "value": k[i].toString(),
            };
            items.push(item);
        }
        component.set("v.accounts", items);
   });
    $A.enqueueAction(action);
  }
})

What i am unable to do is, i am not able to click the Accounts, that i am selecting. How can i do that? Also after clicking, how can i get the corresponding contacts associated with those accounts?

Request you all to kindly guide me on this.

Regards,
Rahul
  • February 13, 2019
  • Like
  • 0