Tag Archives: Apex Class

Salesforce Custom Object to Save Logs

As a Salesforce developer sometimes we face different scenarios, where we need to track production error logs or failed records. To save custom logs, here I have created an object Log__c and a helper class LogHandler, which will help to save custom logs for future references.

Object (Log__c) Fields:

Field Label Field API Name Field Type
Class Class__c Text(255)
Method Method__c Text(255)
Description Description__c Long Text Area(32768)
Line Number Line_Number__c Number(8, 0)
HTTP Response HTTP_Response__c Long Text Area(32768)
HTTP Status Code HTTP_Status_code__c Number(6, 0)
Object Object__c Text(255)
Record Id Record_Id__c Text(255)
Type Type__c Picklist(Success, Error, Information)

Apex Class:

public class LogHandler
{
    //Save information log
    public static void logInformation(String className, String methodName, String description){
        Log__c log = new Log__c();
        log.Class__c = className;
        log.Method__c = methodName;
        log.Description__c = description;
        log.Type__c = 'Information';
        Insert log;
    }
    
    //Save success log
    public static void logSuccessData(String className, String methodName, String description){
        Log__c log = new Log__c();
        log.Class__c = className;
        log.Method__c = methodName;
        log.Description__c = description;
        log.Type__c = 'Success';
        Insert log;
    }
    
    //Save exception log
    public static void logException(String className, String methodName, String description, Integer lineNumber){
        Log__c log = new Log__c();
        log.Class__c = className;
        log.Method__c = methodName;
        log.Description__c = description;
        log.Type__c = 'Error';
        log.Line_Number__c = lineNumber;
        Insert log;
    }
    
    //Save HTTP response log
    public static void logHTTPResponse(String className, String methodName, String description, HttpResponse response){
        Log__c log = new Log__c();
        log.Class__c = className;
        log.Method__c = methodName;
        log.Description__c = description;
        log.Type__c = 'Information';
        if(response != null){
            log.HTTP_Response__c = response.getBody();
            log.HTTP_Status_code__c = response.getStatusCode();			
        }
        Insert log;
    }
    
    //Save result log
    public static void logSaveResult(String className, String methodName, List<Database.SaveResult> saveResultList){
        List<Log__c> logList = new List<Log__c>();
        for (Database.SaveResult sr: saveResultList) {        
            if (sr.isSuccess()) {                    
                Log__c log = new Log__c();
                log.Class__c = className;
                log.Method__c = methodName;
                log.Type__c = 'Success';
                if(sr.getId() != null){
                    log.Object__c = sr.getId().getSObjectType().getDescribe().getName();
                    log.Record_Id__c = sr.getId();
                }
                logList.add(log);                    
            }else{
                Log__c log = new Log__c();
                log.Class__c = className;
                log.Method__c = methodName;
                log.Type__c = 'Error';
                log.Description__c = String.valueOf(sr.getErrors()[0].getMessage());
                logList.add(log);  
            }
        }
        if(!logList.isEmpty()){
            Insert logList;
        }	
    }
    
    //Upsert result log
    public static void logUpsertResult(String className, String methodName, List<Database.UpsertResult> upsertResultList){
        List<Log__c> logList = new List<Log__c>();
        for (Database.UpsertResult ur: upsertResultList) {        
            if (ur.isSuccess()) {                    
                Log__c log = new Log__c();
                log.Class__c = className;
                log.Method__c = methodName;
                log.Type__c = 'Success';
                if(ur.getId() != null){
                    log.Object__c = ur.getId().getSObjectType().getDescribe().getName();
                    log.Record_Id__c = ur.getId();
                }
                logList.add(log);                    
            }else{
                Log__c log = new Log__c();
                log.Class__c = className;
                log.Method__c = methodName;
                log.Type__c = 'Error';
                log.Description__c = String.valueOf(ur.getErrors()[0].getMessage());
                if(ur.getId() != null){
                    log.Object__c = ur.getId().getSObjectType().getDescribe().getName();
                    log.Record_Id__c = ur.getId();
                }
                logList.add(log);  
            }
        }
        if(!logList.isEmpty()){
            Insert logList;
        }	
    }
}

Delete Apex Class or Trigger in Salesforce Production Org Using Eclipse

It is not possible to directly delete an Apex class or trigger after it has been deployed to production. Here are the steps to delete apex class or trigger in Salesforce Production Org by using eclipse and Force.com IDE.

  • Download and Install the Force.com IDE for Eclipse.
  • Connect to the Salesforce Production org.
  • Download the apex class/trigger.
  • Open the meta.xml file of the Apex class/trigger.
  • Change the status of the Apex class/trigger to Deleted.
  • Save and deploy to server.

Note: Apex class status can only be changed to “Active” or “Deleted” and not “Inactive”.

Show required symbol in apex:inputText

Controller:

public with sharing class Sample { 

    public String name {Get;set;}
    
    public Sample() {
    
    }
}

Visualforce Page:

<apex:page controller="Sample">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Name"/>
                    <apex:outputPanel styleClass="requiredInput" layout="block" >
                        <apex:outputPanel styleClass="requiredBlock" layout="block"/>
                        <apex:inputText value="{!name}" required="true"/> 
                    </apex:outputpanel>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output:

Convert Salesforce sObject Record To JSON

Apex Class:

public class ConvertsObjectToJSON
{
    //Return the JSON string from record Id
    public static string getJsonFromSObject(Id recordId)
    {
        String jsonData = '';
        try{
            if(String.isNotBlank(recordId))
            {
                String sObjectFields = '';
                
                //Get sObject Name
                String objName = recordId.getSObjectType().getDescribe().getName();
                
                //Getting the fields information
                Map<String, Schema.sObjectField> sObjectFieldMap = Schema.getGlobalDescribe().get(objName).getDescribe().fields.getMap();
                
                //Map key is the field API name and value is the field data type.
                Map<String, String> fieldMap = new Map<String, String>();
                
                for(Schema.SObjectField sfield: sObjectFieldMap.Values()){
                    Schema.DescribeFieldResult fieldDesc = sfield.getDescribe();
                    fieldMap.put(fieldDesc.getName(), fieldDesc.getType().name());
                }
                
                //Create query with all fields
                for(String field: fieldMap.keySet()){
                    sObjectFields += field+',';
                }
                sObjectFields = sObjectFields.removeEnd(',');
                
                //Dynamic SOQL Query with all fields
                String soqlQuery = 'SELECT '+ sObjectFields +' FROM '+objName+' WHERE Id =: recordId';
                
                //Execute the SOQL query
                sObject sObj = Database.Query(soqlQuery);
                
                //Create JSON
                JSONGenerator gen = JSON.createGenerator(true);
                gen.writeStartArray();
                gen.writeStartObject();
                gen.writeFieldName('attributes');
                gen.writeStartObject();
                gen.writeStringField('type', objName);
                gen.writeEndObject();
                gen.writeFieldName('fields');
                gen.writeStartObject();
                
                for(String field: fieldMap.keySet()){
                    if(sObj.get(field) != null){
                        gen.writeStringField(field, String.ValueOf(sObj.get(field)));
                    }
                    else{
                        gen.writeStringField(field, '');
                    }
                }
                
                gen.writeEndObject();
                gen.writeEndObject();
                gen.writeEndArray();
                //Getting the JSON String Data
                jsonData = gen.getAsString();
            }
        }
        catch(Exception ex){
            
        }
        return jsonData;
    }
}

Invoke the method:

String jsonData = ConvertsObjectToJSON.getJsonFromSObject('001B000000pA7sV');
system.debug('jsonData-' + jsonData);

Populate Picklist from Custom Object to the Visualforce Page

Controller:

public with sharing class Sample
{
    public string selectedValue {get; set;}
    public List<SelectOption> industry {get; set;}
    
    public void getIndustry()
    {
        Schema.DescribeFieldResult industryDescription = Account.Industry.getDescribe();
        industry = new List<SelectOption>();
        
        for (Schema.Picklistentry pl : industryDescription.getPicklistValues())
        {
            industry.add(new SelectOption(pl.getValue(),pl.getLabel()));
        }
    }
    
    public void checkValue()
    {
        System.debug('Selected Industry Type - ' + selectedValue);
    }
}

Visualforce Page:

<apex:page controller="Sample" action="{!getIndustry}" sidebar="false" showHeader="false">
    <apex:form >
        <apex:pageblock>
            <apex:pageBlockSection columns="1" >
                <apex:outputLabel value="Industry Type" />
                <apex:selectList size="1" value="{!SelectedValue}" >
                    <apex:selectOptions value="{!industry}"/>
                    <apex:actionSupport event="onchange" action="{!checkValue}" />
                </apex:selectList>
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>

Output: