Wednesday, May 9, 2018

Build URL to display a case using case number instead of Salesforce CaseID

This can be implemented using below code.

Custom label:  
Name: Case_Number_Details

Value: Please enter the valid 8 character Case Number (e.g. 00123456) after the equal sign in the URL above to view the case details.


Visualforce Page:


<apex:page controller="GetCaseByNumber" title="Get Case By Number" showHeader="false">

  <script>

      if ("{!CaseQuery}".length > 0) {

          if ("{!CaseQuery}" != "<apex:outputText value="{!$Label.Case_Number_Details}"/>" && "{!CaseQuery}" != "You Must Supply a Case Number") window.location = "/{!CaseQuery}";

      }

  </script>

  <h1 style="display:block;margin:25px;font-size:16px;">{!CaseQuery}</h1>


</apex:page>


Apex Class:


public class GetCaseByNumber {

    public static String getCaseQuery () {
       String caseNumberDetails = Label.Case_Number_Details;

        string caseNumber = ApexPages.CurrentPage().getParameters().get('CaseNumber');
        List <Case> c = [SELECT Id FROM Case Where CaseNumber =: caseNumber];
        if (c.size()>0) {
            return string.valueOf(c[0].Id);
        }
        else return caseNumberDetails;

    }    

}

Apex test Class:



private class GetCaseByNumberTest {
    
    static testmethod void TestAccdata(){ 
        Profile prof = [select id from profile where name='System Administrator'];    
        User us      = new User(alias = 'tuser', email='TestUser@testingorg.com',    
                                emailencodingkey='UTF-8', lastname='TestingUser', languagelocalekey='en_US', 
                                localesidkey='en_US', profileid = prof.Id,   
                                timezonesidkey='America/Los_Angeles', username='TestUser@testingorg.com');
        insert us;  
        System.runAs (us) { 
            Account ac = new Account(Name    ='Test', OwnerId  =us.Id);            
            insert ac;
            
            
            Contact cn  = new Contact (FirstName  = 'Test', LastName = 'Test',AccountId = ac.Id,email='testcase@org.com');
            insert cn;
            
            Test.startTest();
            string RTID = [select id from RecordType where SobjectType = 'Case' and Name = 'Support Case'].Id;
            System.assertNotEquals(null,RTID);
            
            case c = new Case(AccountId=ac.Id ,ContactId =  cn.Id,Status='New',Origin='Phone',RecordTypeId = RTID,Subject = 'TestCase',Description ='Test',Product_Type__c = 'My Product);
            
            insert c;
            PageReference myVfPage = Page.getCaseByNumber;
            Test.setCurrentPage(myVfPage);
           ApexPages.currentPage().getParameters().put('CaseNumber',ApexPages.currentPage().getParameters().get(c.CaseNumber));
            
            GetCaseByNumber controller = new GetCaseByNumber();
            GetCaseByNumber.getCaseQuery();
            
            Test.stopTest();
            
        }

    }



Friday, November 10, 2017

How to Convert String to sObject using Apex in Salesforce

Below is the sample code can be used to Convert String to sObject using Apex.

String str = 'Account';
sObject objct = Schema.getGlobalDescribe().get(str).newSObject();
objct.put('Name', 'My Account');
objct.put('Description', 'Description of My Account');
System.debug('sObject - ' + objct);
Below is the output of this code.

SOQL Query to Get the CreatedBy and LastModifiedBy User Name


Below SOQL query can be used to get the CreatedBy and LastModifiedBy User Name


SELECT Id, Name, CreatedBy.FirstName, CreatedBy.LastName, CreatedBy.Name, LastModifiedBy.FirstName, LastModifiedBy.LastName, LastModifiedBy.Name FROM Object__c

Note: Object__c, you can replace for the object you want to get these data.

Tuesday, October 31, 2017

AuraHandledException

From Apex class:

 @AuraEnabled
    public static List<Account> fetchAccount() {
        throw new AuraHandledException('User-defined error');

    }

From client-side controller:

doInit: function(component, event, helper) {
        var action = component.get('c.fetchAccount');
        action.setParams({ firstName : cmp.get("v.firstName") });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.Accounts', response.getReturnValue());
            }
            else if (component.isValid() && state === "ERROR") {
                console.log("Error Message: ", response.getError()[0].message);
            }
        });
        $A.enqueueAction(action);
    }


How to Select All Fields with SOQL in Apex

1. Query All Fields for a Known Record ID:

ID recordId = '5001a00000CgCE2';

DescribeSObjectResult describeResult = recordId.getSObjectType().getDescribe();

List<String> fieldNames = new List<String>( describeResult.fields.getMap().keySet() );

String query =
  ' SELECT ' +
      String.join( fieldNames, ',' ) +
  ' FROM ' +
      describeResult.getName() +
  ' WHERE ' +
      ' id = :recordId ' +
  ' LIMIT 1 '
;

// return generic list of sobjects or typecast to expected type
List<SObject> records = Database.query( query );

System.debug( records );

2. Query All Fields for All Records

The same concept as above but we don’t have a specific record ID, so we need to determine the sobjectype by explicitly specifying the object we’ll query on.

// without an ID, simply specify the object to then derive the sobject type
DescribeSObjectResult describeResult = Account.getSObjectType().getDescribe();

List<String> fieldNames = new List<String>( describeResult.fields.getMap().keySet() );

String query =
  ' SELECT ' +
      String.join( fieldNames, ',' ) +
  ' FROM ' +
      describeResult.getName()
;

// return generic list of sobjects or typecast to expected type
List<SObject> records = Database.query( query );

System.debug( records );