0% found this document useful (0 votes)
12 views12 pages

APEX

Apex is an object-oriented programming language that allows developers to execute flow and transaction control statements on Salesforce servers. It enables developers to add business logic to most system events using syntax similar to Java. Apex code can be used to perform complex validation over multiple objects, create custom transactional logic, and create web services. Apex variables and expressions have data types like primitives, sObjects, collections, and objects from Apex classes.

Uploaded by

nehadupate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views12 pages

APEX

Apex is an object-oriented programming language that allows developers to execute flow and transaction control statements on Salesforce servers. It enables developers to add business logic to most system events using syntax similar to Java. Apex code can be used to perform complex validation over multiple objects, create custom transactional logic, and create web services. Apex variables and expressions have data types like primitives, sObjects, collections, and objects from Apex classes.

Uploaded by

nehadupate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

APEX

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/
apex_intro_get_started.htm

https://www.tutorialspoint.com/apex/index.htm

What is Apex?
Apex is a strongly typed, object-oriented programming language that allows
developers to execute flow and transaction control statements on Salesforce servers
in conjunction with calls to the API. Using syntax that looks like Java and acts
like database stored procedures, Apex enables developers to add business logic to
most system events, including button clicks, related record updates, and
Visualforce pages. Apex code can be initiated by Web service requests and from
triggers on objects.

Apex is also case-insensitive

Apex
Use Apex if you want to:
Perform complex validation over multiple objects.
Create complex business processes that are not supported by workflow.
Create custom transactional logic (logic that occurs over the entire transaction,
not just with a single record or object).
Attach custom logic to another operation, such as saving a record, so that it
occurs whenever the operation is executed, regardless of whether it originates in
the user interface, a Visualforce page, or from SOAP API.
Create Web services.
Create email services.

Data Types

In Apex, all variables and expressions have a data type, such as sObject,
primitive, or enum.
A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or
Boolean (see Primitive Data Types)
An sObject, either as a generic sObject or as a specific sObject, such as an
Account, Contact, or MyCustomObject__c

A collection, including:
A list (or array) of primitives, sObjects, user defined objects, objects created
from Apex classes, or collections (see Lists)
A set of primitives (see Sets)
A map from a primitive to a primitive, sObject, or collection (see Maps)
A typed list of values, also known as an enum (see Enums)
Objects created from user-defined Apex classes (see Classes, Objects, and
Interfaces)
Objects created from system supplied Apex classes
Null (for the null constant, which can be assigned to any variable)

Functional Programming / Object Oriented Programming

Syntax

Data Type
Primitives

Integer --- 1 2 3 4 5 6 ...


String ---- tejas prachi ...
Boolean --- true false
Long .....
Date

-----

Looping

Integer count = 1;
while(count < 11) {
System.debug('The Count is: ' + count);
count++;
}

Integer count = 1;
while(count <= 10) {
System.debug('The Count is: ' + count);
count++;
}

Integer count = 10;


while(count > 0) {
System.debug('The Count is: ' + count);
count--;
}

for(Integer count = 1; count < 11; count++) {


System.debug('The Count is: ' + count);
}

for(Integer count = 10; count > 0; count--) {


System.debug('The Count is: ' + count);
}

-------

Boolean flag = true;


if(flag == true) {
System.debug('Flag is : ' + flag);
}

Boolean flag = true;


if(flag) {
System.debug('Flag is : ' + flag);
}

Boolean flag = false;


if(flag == false) {
System.debug('Flag is : ' + flag);
}
Boolean flag = false;
if(!flag) {
System.debug('Flag is : ' + flag);
}

Boolean flag1 = true;


Boolean flag2 = true;
if(flag1 && flag2) {
System.debug('Flag1 is TRUE : ' + flag1);
System.debug('Flag2 is TRUE : ' + flag2);
}

Boolean flag1 = false;


Boolean flag2 = false;
if(!flag1 && !flag2) {
System.debug('Flag1 is FALSE : ' + flag1);
System.debug('Flag2 is FALSE : ' + flag2);
}

Boolean flag1 = true;


Boolean flag2 = true;
if(flag1) {
System.debug('Flag1 is TRUE : ' + flag1);
if(flag2) {
System.debug('Flag2 is TRUE : ' + flag2);
}
}

Boolean flag1 = true;


Boolean flag2 = false;
if(flag1) {
System.debug('Flag1 is TRUE : ' + flag1);
if(flag2) {
System.debug('Flag2 is TRUE : ' + flag2);
} else {
System.debug('Flag2 is FALSE : ' + flag2);
}
} else {
System.debug('Flag1 is FALSE : ' + flag1);
}

Boolean flag = true;


if(flag) {
System.debug('Flag is TRUE : ' + flag);
} else {
System.debug('Flag is FALSE : ' + flag);
}

---

Integer num = 10;

for(Integer count = 0; count < 12; count++) {


System.debug('I am in the loop');
if(count == 10) {
System.debug('I am in the loop when count = ' + count);
}
}
Integer num = 10;

for(Integer count = 0; count < 12; count++) {


System.debug('I am in the loop');
if(count > 5) {
System.debug('I am in the loop when count = ' + count);
}
}

Boolean isValid = true;


if(isValid == true) {
for(Integer i = 1; i < 11; i++) {
if(math.mod(i,2) != 0) { // math.mod(i,2) -> i % 2 == 0 // odd number check
System.debug(i);
} else {
System.debug('Even Number = ' + i);
}
}
} else {
System.debug('Did not run loop');
}

----

Collections

----

Array

String[] colors = new String[2];


colors[0] = 'Orange';
colors[1] = 'Red';

for(Integer i = 0; i < 2; i++) {


System.debug('Color is: ' + colors[i]);
}

System.debug(colors.size());

for(Integer i = 0; i < colors.size(); i++) {


System.debug('Color is: ' + colors[i]);
}

String[] colors = new String[] {'Red', 'Blue'};

Integer[] numbers = new Integer[10];

// Store days in a week in String array collection


// Sunday Saturday Friday.......

String[] days = new String[] {'Monday', 'Tuesday', 'Wednesday', 'Thursday',


'Friday', 'Saturday', 'Sunday'};
for(Integer i = 6; i >= 0; i--) {
System.debug(days[i]);
}

List<String> myList = new List<String>();


myList.add('Blue');
myList.add('Green');

for(Integer i = 0; i < 2; i++) {


System.debug('Color is: ' + myList.get(i));
}

for(String element : myList) {


System.debug('Color is: ' + element);
}

List<String> colors = new List<String>();


colors.add('Red');
colors.add('Blue');
colors.add('Green');

System.debug('Color at index 0: ' + colors.get(0));


System.debug('Color at index 1: ' + colors.get(1));
System.debug('Color at index 2: ' + colors.get(2));

for(Integer i = 0; i < colors.size(); i++) {


System.debug('Color: ' + colors.get(i));
}

for(String color : colors) {


System.debug('Color in for each loop: ' + color);
}

// Create a list of numbers 1 to 5

List<Integer> numberList = new List<Integer>();


numberList.add(1);
numberList.add(2);
numberList.add(3);
numberList.add(4);
numberList.add(5);

System.debug('Number at index 0 : ' + numbersList.get(0));

for(Integer num : numberList) {


System.debug(num);
}

List<String> colors = new List<String>{


'Yellow',
'Red',
'Green'};
colors.sort();
System.assertEquals('Green', colors.get(0));
System.assertEquals('Red', colors.get(1));
System.assertEquals('Yellow', colors.get(2));

Set<String> myStringSet = new Set<String>();


myStringSet.add('Purple');
myStringSet.add('White');

for(String element : myStringSet) {


System.debug('Color is: ' + element);
}

----- collections example

// Object Oriented Language


// Class Object
// Class is a blueprint....
// Object is a instance of a class
// "new" keyword -> is used to create instance (object) of a class

// Array

// 1, 2, 3, 4, 5 -> collection -> array


// 0 1 2 3 4

/*

Integer[] numbers = new Integer[5];


//index (position)
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;

for(Integer i = 0; i < 5; i++) {


if(numbers[i] != null) {
System.debug('Index = ' + i + ' Value = ' + numbers[i]);
}
}

Integer[] numbers = new Integer[] {1, 2, 3, 4, 5};


for(Integer i = 0; i < 5; i++) {
if(numbers[i] != null) {
System.debug('Index = ' + i + ' Value = ' + numbers[i]);
}
} */

//'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'


// 0 1 2 3 4 5 6
/*Integer[] numbers = new Integer[] {1, 2, 3, 4, 5};
System.debug(numbers.size());

for(Integer num : numbers) {


System.debug(num);
}

String[] days = new String[] {'Sunday', 'Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday', 'Saturday'};
Integer size = days.size();
System.debug('Days in a week are : ' + size);

for(Integer i = 0; i < size; i++) {


System.debug(days[i]);
}

for(String day : days) {


System.debug(day);
} */

// List -> extension of array

/* List<Integer> numbers = new List<Integer>();


numbers.add(12);
numbers.add(22);
numbers.add(33);*/

List<Integer> numbers = new List<Integer> {144, 54, 156, 89};


numbers.sort();
// 54 89 144 156
System.debug(numbers);

List<Integer> descendingNumbers = new List<Integer>();

for(Integer i = numbers.size() - 1; i >=0; i--){


descendingNumbers.add(numbers.get(i));
// 156 144 89 54
}

for(Integer num : descendingNumbers) {


System.debug(num);
}

// Create an list of random numbers and then print the list elements in ascending
order

/* List<Double> randomNumbers = new List<Double>();

for(Integer i = 0; i < 11; i++) {


randomNumbers.add(Math.random());
}

randomNumbers.sort();

System.debug(randomNumbers); */
List<String> colors = new List<String> {'green', 'red', 'blue'};
/* colors.add('red');
colors.add('blue');
colors.add('green'); */

System.debug(colors);

-- APEX SOQL Example

List<Contact> contactList = [SELECT Id, Name from Contact];


for(Contact contact : contactList) {
System.debug('Contact Id is : ' + contact.Id + ' Contact Name is : ' +
contact.name);
}

-----

Apex CRUD Example

/* This class provides methods to read, create, update and delete account records
*/
public class AccountService {

/* This method returns a list of accounts based on the name provided in the
input */
public List<Account> getAccounts(String accountName) {
List<Account> output = [SELECT Id, Name FROM Account WHERE Name
=:accountName];
if(output == null || output.size() == 0) {
System.debug('There is no account with name = ' + accountName);
} else {
System.debug(output);
}

return output;

/* This method creates an account record */


public Account createAccount(String accountName) {
Account acc = new Account();
acc.Name = accountName;
insert acc;
return acc;
}

/* This method finds account by given name and updates the accountSite field */
public void updateAccount(String accountName, String accountSite) {
List<Account> accounts = [SELECT Id, Name, Site FROM Account WHERE
Name=:accountName];
for(Account acc : accounts) {
acc.Site = accountSite;
}
update accounts;
}

/* This method deletes all accounts whose name is equal to input provided name
from user */
public void deleteAccount(String accountName) {
List<Account> accounts = [SELECT Id, Name, Site FROM Account WHERE
Name=:accountName];
if(accounts != null && accounts.size() > 0) {
delete accounts;
}
}

-------

Anonymous Window

AccountService service = new AccountService();


service.createAccount('Hindustan Copper');

----

https://trailhead.salesforce.com/content/learn/modules/apex_testing/
apex_testing_intro

----

test class

@isTest
public class AccountServiceTest {

@isTest(SeeAllData=true)
public static void testGetAccount() {
AccountService service = new AccountService();
List<Account> result = service.getAccounts('Edge Communications');
System.assertEquals(1, result.size());
}

@isTest()
public static void testCreateAccount() {
AccountService service = new AccountService();
Account result = service.createAccount('Tesla Cars');
System.Assert.isNotNull(result, 'Account is not null');
}

/// Index Value


// [11,22,33,44,55]
// 0 1 2 3 5
// List -> {Account1, Account2, Account3}
// //////// 0 1 2

@isTest(SeeAllData=true)
public static void testUpdateAccount() {
AccountService service = new AccountService();
service.updateAccount('Dickenson plc', 'www.testme.com');
List<Account> result = service.getAccounts('Dickenson plc');
Account resultAccount = result.get(0);
System.assertEquals('www.testme.com', resultAccount.Site);
}

@isTest
public static void testDeleteAccount() {
AccountService service = new AccountService();

Account resultBeforeDelete = service.createAccount('Apex Test Account');


Assert.isNotNull(resultBeforeDelete);

service.deleteAccount('Apex Test Account');

List<Account> resultAfterDelete = service.getAccounts('Apex Test Account');

System.assertEquals(0, resultAfterDelete.size());
}

----

public class CalculatorService {

public Integer add(Integer num1, Integer num2) {


Integer sum = num1 + num2;
return sum;
}

public Integer subtract(Integer num1, Integer num2) {


Integer difference = num1 - num2;
return difference;
}
}

--- test

@isTest
public class CalculatorServiceTest {

@isTest
public static void testAddTwoNumbers() {
CalculatorService service = new CalculatorService();
Integer result = service.add(1, 2);
System.assertEquals(3, result);
}

@isTest
public static void testSubtractTwoNumbers() {
CalculatorService service = new CalculatorService();
Integer result = service.subtract(3, 2);
System.assertEquals(1, result);
}
}

-----

Use Case

Write an Apex class to create Task (Standard Object) record for opportunities that
are NOT closed and close date is less than TODAY and stage name is Negotiation.

public class OpportunityTaskService {

public void createTask() {

List<Opportunity> oppList = [SELECT Id, Name, StageName, CloseDate, OwnerId


FROM Opportunity WHERE IsClosed = false AND CloseDate < TODAY AND StageName LIKE
'%Negotiation%'];

// We want to loop on all opportunies returned by above query


// We want to create task for each opportunity
// DML -? Data manupliation language
// Shared Resource = CPU

List<Task> taskList = new List<Task>();

// Check if oppsList is NOT empty

//if(oppsList != null && oppsList.size() > 0)

if(!oppList.isEmpty()) {
for(Opportunity opp : oppList) {
Task tsk = new Task();
tsk.Subject = 'Reminder Task for Opportunity';
tsk.Priority = 'Normal';
tsk.Status = 'Not Started';
tsk.OwnerId = opp.OwnerId;
tsk.WhatId = opp.Id;
taskList.add(tsk);
}
}

// Bulkification
if(!taskList.isEmpty()) {
insert taskList;
}

}
}

--- test

@isTest()
public class OpportunityTaskServiceTest {

@isTest()
public static void testCreateTask() {
// Create an opportunity test record to match the conditions
Opportunity opp = new Opportunity();
opp.Name = 'Test Opp';
opp.StageName = 'Negotiation/Review';
opp.CloseDate = Date.newInstance(2022, 12, 9);
insert opp;

OpportunityTaskService service = new OpportunityTaskService();


service.createTask();

List<Task> taskList = [SELECT Id from Task];


System.assertEquals(1, taskList.size());
}
}

You might also like