Category Archives: Salesforce

Generate Json Data Using Apex in Salesforce

Child Class:

public class Child{

    public String Name;
    
    public Child(String name) {
        this.Name = name;
    }
}

Parent Class:

public class Parent{

    public Child[] ChildRecords;
    public String Name;
    
    public Parent(String Name) {
        this.Name = name;
        ChildRecords = new Child[0];
    }
}

Pass parameters to above class using below code:

//Select Account Id from Account Object
String accountId = '0012800001A4UgG';

//Select Account & Contact Records
Account acc = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account WHERE Id =: accountId];

//Create a parent record
Parent par = new Parent(acc.Name);

//Loop on Contacts
for(Contact con: acc.Contacts) {
    par.childRecords.add(new Child(con.Name));
}

//Get the Json data
String jsonData = JSON.serialize(par);
System.debug('JsonData-' + jsonData);

Here is the debug log snapshot of Json data:
Json Data

Note: This is the sample class. You can modify it as per your requirement.

Salesforce HTTP Status code and Error Responses

HTTP Status Code Description
200 “OK” success code, for GET,PATCH or HEAD request.
201 “Created” success code, for POST request.
204 “No Content” success code, for DELETE request.
300 The value returned when an external ID exists in more than one record. The response body contains the list of matching records.
304 The request content has not changed since a specified date and time. The date and time is provided in a “If-Modified-Since” header.
400 The request could not be understood, usually because the ID is not valid for the particular resource. For example, if you use a userId where a groupId is required, the request returns 400.
401 The session ID or OAuth token has expired or is invalid. Or, if the request is made by a guest user, the resource isn’t accessible to guest users. The response body contains the message and errorCode.
403 The request has been refused. Verify that the context user has the appropriate permissions to access the requested data, or that the context user is not an external user.
404 Either the specified resource was not found, or the resource has been deleted.
405 The method specified in the Request-Line isn’t allowed for the resource specified in the URI.
409 A conflict has occurred. For example, an attempt was made to update a request to join a group, but that request had already been approved or rejected.
412 A precondition has failed. For example, in a batch request, if haltOnError is true and a subrequest fails, subsequent subrequests return 412.
415 The entity in the request is in a format that’s not supported by the specified method.
500 An error has occurred within Force.com, so the request could not be completed. Contact Salesforce Customer Support.
503 Too many requests in an hour or the server is down for maintenance.

Recall Approval Process Using Apex In Salesforce

Sample Code:

//Object record id to recall the approval process
String recordId = '0065800000lQxxsAAC';
//Get Process Instance Work Items
ProcessInstanceWorkitem[] piWorkItems = [SELECT Id FROM ProcessInstanceWorkItem WHERE ProcessInstance.TargetObjectId = :recordId
                                         AND ProcessInstance.Status = 'Pending']; 
if(piWorkItems.size() > 0){
    //Create Process Work Item Request
    Approval.ProcessWorkItemRequest pwiRequest = new Approval.ProcessWorkItemRequest();
    pwiRequest.setAction('Removed');
    pwiRequest.setWorkItemId(piWorkItems[0].Id);
    Approval.ProcessResult result = Approval.process(pwiRequest);
}

Difference between Remote Action and Action Function in Salesforce

Here are some differences between apex:actionFunction and @RemoteAction.

Remote Action Function:

  • Remote Action is an Apex annotation used to mark a method as being available for javascript remoting.
  • Remote Action can call the apex methods from any apex class.
  • Remote Action allows you to call the method from javascript yourself and retrieve the result as a javascript object for manipulation.
  • Remote Action methods are static and global, hence don’t have access to your current controller variables and methods.
  • Remote Action methods require less bandwidth, and server processing time, because only the data you submit is visible and the view state is not transferred.
  • Remote Action methods have to update the DOM manually using explicit JavaScript.
  • Remote Action methods can return data directly back to the calling JavaScript, but cannot update the page’s view state.

Action Function:

  • Action Function is a Visualforce tag allows you to invoke a controller action from the Visualforce Page asynchronously via AJAX requests.
  • Action Function can call the apex methods only from the class linked to the Visualforce page.
  • Action Function doesn’t let you get retrieve data but you can rerender the page or a specific section of the page to update it with new values from the controller instance.
  • Action Function methods are instance methods, and so can see the entire page state.
    Action Function has to transfer the page view state.
  • Action Function methods automatically update the Visualforce DOM and can refresh part or all of the page, and can provide a standard interface for showing a loading status through apex:actionStatus.
  • Action Function methods can update the page’s view state, but cannot return data directly back to JavaScript (although you can do this with some extra effort using oncomplete).

In general, apex:actionFunction is easier to use and requires less code, while @RemoteAction offers more flexibility. Moreover, @RemoteAction helps in reducing View State size and also provides you near real time transaction.
.