Sales Force Syntax Notes

Important syntax 

Trigger Syntax

Trigger TriggerName ObjectName(TriggerEvents){
if(Tirgger.IsContextvariable   && Tirgger.IsContextvariable ){
}
}
Example :
trigger Account_AfterInsert_Trigger on Account(after insert){
if(Trigger.isAfter && Trigger.isInsert){
}
}
Note: Trigger.New Is not available in Before delete Trigger

Batch class Syntax 

global class MyBatchClass implements Database.Batchable<sObject> {
    global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {
        // collect the batches of records or objects to be passed to execute
// string query='SELECT Id,Name from Account';
        //return database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext bc, List<P> records){
        // process each batch of records
    } 
    global void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }

}

DataBase.saveResult Syntax :
// Create two accounts, one of which is missing a required field
Account[] accts = new List<Account>{
new Account(Name='Account1'),
new Account()};
Database.SaveResult[] srList = Database.insert(accts, false);

// Iterate through each returned result
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// Operation was successful, so get the ID of the record that was processed
System.debug('Successfully inserted account. Account ID: ' + sr.getId());
}
else {
// Operation failed, so get all errors             
for(Database.Error err : sr.getErrors()) {
System.debug('The following error has occurred.');                 
System.debug(err.getStatusCode() + ': ' + err.getMessage());
System.debug('Account fields that affected this error: ' + err.getFields());
}
}
}

Schedule Class Syntax 

    global class SomeClass implements Schedulable {
    global void execute(SchedulableContext ctx) {
        // awesome code here
    }
}
execution of schedule :
ScheduleClassName reminder = new ScheduleClassName();
// Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
String sch = '20 30 8 10 2 ?';
String jobID = System.schedule('Remind Opp Owners', sch, reminder);
    Abrupt schedule job :
   System.abortJob(JobId);
 
Single Email MEssaging Syntax :

Messaging.singleEmailmessage Email =new Messaging.singleEmailmessage();
email.setsubject('Subject');
email.SetPlainTextbody('email_body');
Email.SetToAddresses(emailsList);
Messaging.sendemailResult[] r = Messaging.sendemail(new Messaging.singleEmailmessage[]{email});
MassEmail Syntax :
EmailTemplate TemplateId=[Select id from EmailTemplate where name = 'EmailTemplateName' limit 1];
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
mail.setTargetObjectIds(lstIds);
mail.setSenderDisplayName('SfdcNotification');
mail.setTemplateId(TemplateId);
Messaging.sendemailResult[] results =Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
Email success syntax : for(Messaging.SendEmailResult result :results){
if( result.success){
//code
}
}

Test Class Syntax : 
Note : Never use sellAlldata=true; testMethods should not retrun any data
@isTest
Private class testClassname(){
@testSetUp
public void testData(){
// Prepare your data
}
@isTest static void testName() {
test.starttest();
// new limits will start for this block of code
test.Stoptest();
// code_block
}
static testMethod void testName() {
// code_block
}

}



Rest Web service example :
public class AnimalsCallouts {
    public static HttpResponse makeGetCallout() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {
            // Deserializes the JSON string into collections of primitive data types.
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            // Cast the values in the 'animals' key as a list
            List<Object> animals = (List<Object>) results.get('animals');
            System.debug('Received the following animals:');
            for (Object animal: animals) {
                System.debug(animal);
            }
        }
        return response;
    }
    public static HttpResponse makePostCallout() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setBody('{"name":"mighty moose"}');
        HttpResponse response = http.send(request);
        // Parse the JSON response
        if (response.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug(response.getBody());
        }
        return response;
    }     
}

Test Class syntax for web services :
  Static resource example :
  @isTest
private class AnimalsCalloutsTest {
@isTest static  void testGetCallout() {
// Create the mock response based on a static resource
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('GetAnimalResource');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
// Associate the callout with a mock response
Test.setMock(HttpCalloutMock.class, mock);
// Call method to test
HttpResponse result = AnimalsCallouts.makeGetCallout();
// Verify mock response is not null
System.assertNotEquals(null,result,
'The callout returned a null response.');
// Verify status code
System.assertEquals(200,result.getStatusCode(),
  'The status code is not 200.');
// Verify content type 
System.assertEquals('application/json;charset=UTF-8',
  result.getHeader('Content-Type'),
  'The content type value is not expected.');
// Verify the array contains 3 items   
Map<String, Object> results = (Map<String, Object>)
JSON.deserializeUntyped(result.getBody());
List<Object> animals = (List<Object>) results.get('animals');
System.assertEquals(3, animals.size(),
  'The array should only contain 3 items.');       

}
TestClass syntax for mock responce  
First Create a mock class 
@isTest
global class AnimalsHttpCalloutMock implements HttpCalloutMock {
// Implement this interface method
global HTTPResponse respond(HTTPRequest request) {
// Create a fake response
HttpResponse response = new HttpResponse();
response.setHeader('Content-Type', 'application/json');
response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
response.setStatusCode(200);
return response;
}
}

Use mock class in main test Class

@isTest static void testPostCallout() {
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new AnimalsHttpCalloutMock());
// This causes a fake response to be sent
// from the class that implements HttpCalloutMock.
HttpResponse response = AnimalsCallouts.makePostCallout();
// Verify that the response received contains fake values
String contentType = response.getHeader('Content-Type');
System.assert(contentType == 'application/json');
String actualValue = response.getBody();
System.debug(response.getBody());
String expectedValue = '{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}';
System.assertEquals(actualValue, expectedValue);
System.assertEquals(200, response.getStatusCode());
}

Expose the class as rest service :

@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
@HttpGet
global static Account getRecord() {
// Add your code
}
}
@HttpGet Read Reads or retrieves records.
@HttpPost Create Creates records.
@HttpDelete Delete Deletes records.
@HttpPut Upsert Typically used to update existing records or create records.
@HttpPatch Update Typically used to update fields in existing records.


Expose a Class as a SOAP Service

global with sharing class MySOAPWebService {
webservice static Account getRecord(String id) {
// Add your code
}
}

Test Class inBound rest  Request :
@IsTest
private class CaseManagerTest {
@isTest static void testGetCaseById() {
Id recordId = createTestRecord();
// Set up a test request
RestRequest request = new RestRequest();
request.requestUri =
'https://yourInstance.salesforce.com/services/apexrest/Cases/'
+ recordId;
request.httpMethod = 'GET';
RestContext.request = request;
// Call the method to test
Case thisCase = CaseManager.getCaseById();
// Verify results
System.assert(thisCase != null);
System.assertEquals('Test record', thisCase.Subject);
}
@isTest static void testCreateCase() {
// Call the method to test
ID thisCaseId = CaseManager.createCase(
'Ferocious chipmunk', 'New', 'Phone', 'Low');
// Verify results
System.assert(thisCaseId != null);
Case thisCase = [SELECT Id,Subject FROM Case WHERE Id=:thisCaseId];
System.assert(thisCase != null);
System.assertEquals(thisCase.Subject, 'Ferocious chipmunk');
}
@isTest static void testDeleteCase() {
Id recordId = createTestRecord();
// Set up a test request
RestRequest request = new RestRequest();
request.requestUri =
'https://yourInstance.salesforce.com/services/apexrest/Cases/'
+ recordId;
request.httpMethod = 'GET';
RestContext.request = request;
// Call the method to test
CaseManager.deleteCase();
// Verify record is deleted
List<Case> cases = [SELECT Id FROM Case WHERE Id=:recordId];
System.assert(cases.size() == 0);
}
@isTest static void testUpsertCase() {
// 1. Insert new record
ID case1Id = CaseManager.upsertCase(
'Ferocious chipmunk', 'New', 'Phone', 'Low', null);
// Verify new record was created
System.assert(Case1Id != null);
Case case1 = [SELECT Id,Subject FROM Case WHERE Id=:case1Id];
System.assert(case1 != null);
System.assertEquals(case1.Subject, 'Ferocious chipmunk');
// 2. Update status of existing record to Working
ID case2Id = CaseManager.upsertCase(
'Ferocious chipmunk', 'Working', 'Phone', 'Low', case1Id);
// Verify record was updated
System.assertEquals(case1Id, case2Id);
Case case2 = [SELECT Id,Status FROM Case WHERE Id=:case2Id];
System.assert(case2 != null);
System.assertEquals(case2.Status, 'Working');

@isTest static void testUpdateCaseFields() {
Id recordId = createTestRecord();
RestRequest request = new RestRequest();
request.requestUri =
'https://yourInstance.salesforce.com/services/apexrest/Cases/'
+ recordId;
request.httpMethod = 'PATCH';
request.addHeader('Content-Type', 'application/json');
request.requestBody = Blob.valueOf('{"status": "Working"}');
RestContext.request = request;
// Update status of existing record to Working
ID thisCaseId = CaseManager.updateCaseFields();
// Verify record was updated
System.assert(thisCaseId != null);
Case thisCase = [SELECT Id,Status FROM Case WHERE Id=:thisCaseId];
System.assert(thisCase != null);
System.assertEquals(thisCase.Status, 'Working');
}
// Helper method
static Id createTestRecord() {
// Create test record
Case caseTest = new Case(
Subject='Test record',
Status='New',
Origin='Phone',
Priority='Medium');
insert caseTest;
return caseTest.Id;
}       
}

Test Class for web service Mock :
Test.setMock(WebServiceMock.class, new MyWebServiceMockImpl());
--
example : create a WebServiceMock
@isTest
global class CalculatorCalloutMock implements WebServiceMock {
   global void doInvoke(
           Object stub,
           Object request,
           Map<String, Object> response,
           String endpoint,
           String soapAction,
           String requestName,
           String responseNS,
           String responseName,
           String responseType) {
        // start - specify the response you want to send
        calculatorServices.doAddResponse response_x =
            new calculatorServices.doAddResponse();
        response_x.return_x = 3.0;
        // end
        response.put('response_x', response_x);
   }
}
----

call this mockclass in main test class
@isTest
private class AwesomeCalculatorTest {
    @isTest static void testCallout() {           
        // This causes a fake response to be generated
        Test.setMock(WebServiceMock.class, new CalculatorCalloutMock());
        // Call the method that invokes a callout
        Double x = 1.0;
        Double y = 2.0;
        Double result = AwesomeCalculator.add(x, y);
        // Verify that a fake result is returned
        System.assertEquals(3.0, result);
    }
}

================================================
Lighting component syntax :
Application event syntax :
 Create : <aura:event type="APPLICATION" description="Event template" >
    <aura:attribute name="typeId" type="string"/>
</aura:event>

Handle  an event on  component 
<aura:handler event="c:NewUser" action="{!c.Action}"/>
action {
event.getParam("typeId");
 }
Fire an event
<aura:registerEvent name="appEvent" type="c:appEvent"/> register
var appEvent = $A.get("e.c:appEventName");
appEvent.setParams({ "typeId" : myValue }); // to set values to event
appEvent.fire(); // fire
==========================
Calling a apex class method 
===========================
var action = componet.get("c.methodName);
 action.setParams({
             "accountIdAsString" : value,
"secondParameter" : value2
         });

  action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
               // sucesscode
            }
            else if (state === "INCOMPLETE") {
                // do something
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " +
                                 errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        })

$A.enqueueAction(action);
Using lighting Component IN VF page :
<apex:includeLightning />
extends="ltng:outApp"
$Lightning.use(): – Refer the lightning application that we are using.
$Lightning.createComponent(): – Used to dynamically creating the lightning component.

Methods in Lighting Components ;

<aura:method name="sampleMethod" action="{!c.doAction}"
  description="Sample method with parameters">
    <aura:attribute name="param1" type="String" default="parameter 1"/>
    <aura:attribute name="param2" type="Object" />
</aura:method>


({
    doAction : function(cmp, event) {
        var params = event.getParam('arguments');
        if (params) {
            var param1 = params.param1;
            // add your code here
        }
    }
})


Get Resource from static resource
$A.get(‘$Resource.resourceName’).

Css toggle :
$A.util.toggleClass(cmp, ‘class’)

3 comments:

  1. Do you need a quick long or short term loan with a relatively low interest rate as low as 2% .
    We offer business loan, personal loan, home loan, auto loan, student loan, debt consolidation loan e t c .
    We are guaranteed in giving out financial services .
    Do you need urgent funding Apply now ?
    We offer personal, commercial and personal finance for
    Home Improvement finance
    Inventor finances
    Auto finances
    Debt Consolidation
    Line of Credit
    Second Mortgage
    Business finances
    Personal finances
    International finance

    Please write back If Interested.
    Email us: creditosantajusta@gmail.com
    Phone number : +1 (659) 210‑0433 (Call/Whats app)
    Investor Joe Mentor

    ReplyDelete
  2. I live in UK London and i am a happy woman today? and i
    told my self that any lender that rescue my
    family from our poor situation, i will refer
    any person that is looking for loan to him,
    he gave me happiness to me and my family, i
    was in need of a loan of $250,000.00 to
    start my life all over as i am a single
    mother with 3 kids I met this honest and GOD
    fearing man loan lender that help me with a
    loan of $250,000.00 U.S. Dollar, he is a GOD
    fearing man, if you are in need of loan and
    you will pay back the loan please contact
    him tell him that is Mrs. Phyllis Sue South that
    refer you to him. contact Mr. Anthony Mitchell
    via email: (applicantonline3@gmail.com OR creditosantajusta@gmail.com)

    ReplyDelete