Posts

Showing posts from 2019

Salesforce: Read JSON Data in Apex class and map with object instance

//JSON Request/Body from the Server/External system String response = '[ {  "name": "account1", "Phone": "12345", "Opportunities" : {records:[{ "name": "opportunity1", "StageName": "1 - Qualified Lead"},{ "name": "opportunity2", "StageName": "1 - Qualified Lead"}]} }, {  "name": "account1", "Phone": "12345" } ]'; //Parse the JSON Body into List of Object (Key with value) List<Object> accountResponse = (List<Object>)JSON.deserializeUntyped(response); Map<String, Object> jsonResponseOpportunityValues; List<Account> AccountList = (List<Account>)JSON.deserialize(response, List<Account>.class); List<Opportunity> OpportunityList = new List<Opportunity>(); //Read one by one list of object instance values to retrive the child object Instance values for(Object ...

Salesforce : Insert parent and child record with Single DML Operation

STEP 1 //******Create the external unique Id field in the parent object**** STEP 2 //create the Parent object instance Account accountRecord = new Account(Name ='Test1',sample_uniqueField__c='12345'); //create the parent record instance with unique key field reference Account caseRecordWithKey = new Account(sample_uniqueField__c='12345'); //create the child record Instance and map with the parrent record instance Opportunity opportunityRecord = new Opportunity(name='Test'2,Accounts = caseRecordWithKey); //add both parent and child records instance into one SObject list SObject[] sobjList = new List<SObject>(); sobjList.add(accountRecord); sobjList.add(opportunityRecord); //perform the DML operation Database.SaveResult[] results = Database.insert(sobjList);

Salesforce: Dynamically Submit the record for Approval process

Approval.ProcessSubmitRequest processSubmitRequest = new Approval.ProcessSubmitRequest(); processSubmitRequest.setComments('Submitting request for approval.'); processSubmitRequest.setObjectId(*******PASS RECORD ID*********); processSubmitRequest.setSubmitterId(userInfo.getUserId()); // Submit the record to specific process and skip the criteria evaluation processSubmitRequest.setProcessDefinitionNameOrId(*********MENTION THE APPROVAL PROCESS NAME************); processSubmitRequest.setSkipEntryCriteria(true); // Submit the approval request for the account Approval.ProcessResult result = Approval.process(processSubmitRequest);

Salesforce: Reassigning Pending Approval Request using Apex Class

String selectedRecordId = ******PASS THE TARGET OBJECT RECORD ID*******; //If there are multiple approvers then it return multiple records List<ProcessInstanceWorkitem> ProcessInstanceWorkitemRecordList = new List<ProcessInstanceWorkitem>(); for(ProcessInstanceWorkitem ProcessInstanceWorkitemRecord :[SELECT ProcessInstanceId,actorId FROM ProcessInstanceWorkitem WHERE ProcessInstance.TargetObjectId=:selectedRecordId]) { if(!String.valueOf(ProcessInstanceWorkitemRecord.actorId).startsWith('005') && ProcessInstanceWorkitemRecordList.size()==0){ ProcessInstanceWorkitemRecord.actorId = UserInfo.getUserId(); ProcessInstanceWorkitemRecordList.add(ProcessInstanceWorkitemRecord); } else if(ProcessInstanceWorkitemRecord.actorId == UserInfo.getUserId()){ ProcessInstanceWorkitemRecordList = new List<ProcessInstanceWorkitem>(); break; } } if(ProcessInstanceWorkitemRecordList.size()>0) UPDATE ProcessInstanceWorkitemRecordList;

Salesforce: Dynamically approve the approval process record using Apex Class

public void approveRecord(Id objectRecordId) { Id processInstanceWorkitemInstance = [SELECT Id FROM ProcessInstanceWorkitem WHERE ProcessInstance.TargetObjectId = :objectRecordId].id; Approval.ProcessWorkitemRequest processWorkitemRequestInstance = new Approval.ProcessWorkitemRequest(); processWorkitemRequestInstance.setComments('record approved'); processWorkitemRequestInstance.setAction('Approve'); processWorkitemRequestInstance.setWorkitemId(processInstanceWorkitemInstance); Approval.ProcessResult result = Approval.process(processWorkitemRequestInstance); }

Salesforce: Dynamically Create Apex Class and Apex Test Class using Tooling API

//Creating the Apex Class JSON Body String classMethod = 'public String DynamicClassMethod (string methodName) { return methodName; }'; String classBody = 'Public Class DynamicClass { '; classBody += classMethod + '}'; //Creating the Apex Test Class JSON Body String testClassBody = '@isTest private Class DynamicClassTest { '; String methodParameter = 'testName'; String testClassMethodInstance = ' DynamicClass DynamicClassInstance = new DynamicClass(); '; testClassMethodInstance += ' DynamicClass.DynamicClassMethod( \''+methodParameter+'\');'; testClassBody += testClassMethodInstance + '}'; String sessionId = UserInfo.getSessionID(); String endpointURL = URL.getSalesforceBaseUrl().toExternalForm(); HttpResponse httpResponseBody; String jsonBody; //Check whether class already created or not? List<ApexClass> apexClasssList = [SELECT id FROM ApexClass WHERE Name = 'DynamicClass']; //If Class...

Salesforce: Display map values in the Visualforce page

<apex:pageBlockTable value="{!recordMap}" var="record"> <apex:column headerValue="id" value="{!recordMap[record].Id}"/> <apex:column headerValue="name" value="{!recordMap[record].name}"/> <apex:pageBlockTable>

Salesforce: Pass the parameter from page block table to apex class

//Visualforce page pageblock table:     <apex:pageBlockTable value="{!recordList}" var="record">         <apex:column headerValue="ACTION" styleClass="fixedColumnWidth" headerClass="alignCenter">             <apex:commandButton action="{!removeRecord}" value="REMOVE" reRender="resultTable" status="popUpPageLoading">                 <apex:param name="selectedRecordId" value="{!record.Id}"/>             </apex:commandButton>         </apex:column>     <apex:pageBlockTable> //Apex Class public void removeRecord() {                String selectedRecordId = Apexpages.currentPage().getParameters().get('selectedRecordId'); }

Salesforce: Convert the date value in the logged in user local time format on Apex class

//Apex class Convert the time into local formate DateTime createdDate = [SELECT CreateDate FROM Account LIMIT 1].CreatedDate; Integer timeOffset = UserInfo.getTimezone().getOffset(createdDate); createdDate = createdDate.addSeconds(timeOffset/1000); 

Salesforce: Dynamically Assign the Salesforce standard icons in the Visualforce page

//VF Page code     <apex:pageBlockTable value="{!recordList}" var="record">         <apex:column headerValue="Icon">            <apex:image id="theImage" value="{!record.colorCode}"/>         </apex:column>     </apex:pageBlockTable> //Apex Class to get the values     public List<accountRecord> recordList {get; set;} public void getAccount() {    recordList = new List<accountRecord>();    for(Account record:[SELECT CreatedDate FROM Account]) {               String colorCode = (record.CreatedDate>System.Now().addDays(-3))?'/img/samples/flag_green.gif':(record.CreatedDate>System.Now().addDays(-5))?'/img/samples/flag_yellow.gif':'/img/samples/flag_red.gif';        recordList.add(new accountRecord(colorCode));    } } public cla...

Salesforce: Dynamically Assign the style in the Visualforce page

//CSS Style  .red {             background-color: red;         }         .green {             background-color: green;         }         .yellow {             background-color: green;         }       //VF Page code     <apex:pageBlockTable value="{!recordList}" var="record">         <apex:column styleClass="{!record.colorCode}" headerValue="Created Date">            {!record.createdDate}         </apex:column>     </apex:pageBlockTable>       //Apex Class to get the values    public List<accountRecord> recordList {get; set;} public void getAccount() { recordList = new List<accoun...

Salesforce: Pagination in Visualforce Page

Pagination on the Visualforce page: //Created First,Next,Last,Previous button along with number of record count  <apex:outputPanel rendered="{!taskTotalRecordCount>0}" layout="block" styleClass="pageblockIconBlock">         <apex:commandButton styleClass="pageblockIconStyle" value="<<" status="pageLoading" rerender="resultTable" action="{!FirstPageCompletedTaskData}" disabled="{!preveviousdata}"/>         <apex:commandButton styleClass="pageblockIconStyle" value="<" status="pageLoading" rerender="resultTable" action="{!PreviousPageCompletedTaskData}" disabled="{!preveviousdata}"/>                <apex:outputText style="padding-left:15px;padding:5px;" >&nbsp;&nbsp;{!(taskCompletedRecordOffsetSize+1)}-{!IF((taskCompletedRecordOffsetSize + taskCompletedRecordLimitSize)>taskTota...

SALESFORCE: Dynamically assign the approval process record to different user using Apex class

Dynamically assign the approval process to the different user using apex class: STEPS : //Get the approval process instance workitem record, which has a current approver details List<ProcessInstanceWorkitem> processInstanceWorkItemList = [select ProcessInstanceId,actorId from ProcessInstanceWorkitem where ProcessInstance.TargetObjectId=********MENTION THE TARGET OBJECT RECORD ID********]; //Assign the user or group id whom you want to assign the approval process processInstanceWorkItemList[0].actorId=********MENTION THE USER/GROUP RECORD ID********; //Update the list, it will internally create the new record in ProcessInstanceStep to capture the latest user detail and update the current approver in the approval process update processInstanceWorkItemList;