Creating ContactController Class - Salesforce Lightning
- Salesforce Lightning applications make it easy to work with data.
- In this module, you create an Apex controller that allows your Lightning application to retrieve contacts, or to Search contacts by name or by id.
What you will learn
- Create an Apex Controller that exposes data and logic to the client application
Steps:
- Open Developer Console, by Clicking your name in the upper right corner screen.
- Click on File | New | Apex Class specify ContactController as the class name and click Ok.
Implement the ContactController Class as follows :
public with sharing class ContactController { @AuraEnabled public static List findAll() { return [ SELECT Id, Name, Phone FROM Contact LIMIT 25]; } @AuraEnabled public static List findByName(String searchKey) { String name ='%'+searchKey+'%'; return[ SELECT Id, Name, Phone FROM Contact WHERE Name like : name Limit 25]; } @AuraEnabled public static Contact findById(String contactId) { return[SELECT Id, Name, Title, Phone, account.Name FROM Contact where Id=:contactId]; }}
ContactController is a regular controller class with methods to retrieve contacts (findAll), or to search contacts by name (findByName) or by id (findById).public with sharing class ContactController
{
@AuraEnabled
public static List findAll()
{
return [ SELECT Id, Name, Phone FROM Contact LIMIT 25];
}
@AuraEnabled
public static List findByName(String searchKey)
{
String name ='%'+searchKey+'%';
return[ SELECT Id, Name, Phone FROM Contact WHERE Name like : name Limit 25];
}
@AuraEnabled
public static Contact findById(String contactId)
{
return[SELECT Id, Name, Title, Phone, account.Name FROM Contact where Id=:contactId];
}
}
The @AuraEnabled method annotation makes a method available to Lightning applications
Click File > Save to save the file