It
is the in-house technology of salesforce.com which is similar to Java programming
with object oriented concepts and to write our own custom logic
Showing posts with label APEX. Show all posts
Showing posts with label APEX. Show all posts
Tuesday, January 21, 2014
Thursday, July 19, 2012
Iterating Map using for loop in Apex Class
You can user keyset() method to iterate over keys in map to fetch values
Apex Class:
Map<String,String> fieldList = new Map<String,String>{‘Name__c’=>’Name’, ‘Age__C’=>’Age’};
for (String fieldName : fieldList.keySet()){
system.debug(fieldName);
}
Thursday, June 21, 2012
To send Email from Apex using email Template
To use an Email Template from Apex Class in order to send an email:
In order to send an email from apex class, you can use any of the below messaging objects.
Single Email Messaging :
Instantiates the object to send single email message.
Ex: To send single email to a selected Contact.
public void SendEmail()
{
contact con=[Select id from contact limit 1];
EmailTemplate et=[Select id from EmailTemplate where name=:'EmailTemplatename'];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(con.Id);
mail.setSenderDisplayName('Charan Tej');
mail.setTemplateId(et.id);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
For other object methods of Single Email Messaging, Click Here
Note: Do remember that we can send only 10 emails in method invocation of Apex class using SingleEmailMessage.
Mass Email Messaging:
Instantiates the object to send mass email message.
Ex: To send mass email to a Contacts.
public void SendEmail()
{
List<contact> lstcon=[Select id from contact limit 200];List<Id> lstids= new List<Id>();for(Contact c:lstcon){lstids.add(c.id);
}
EmailTemplate et=[Select id from EmailTemplate where name=:'EmailTemplatename'];Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();mail.setTargetObjectIds(lstIds);mail.setSenderDisplayName('Charan Tej');mail.setTemplateId(et.id);Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
}
For other object methods of Mass Email Messaging, Click Here
Apex Callout
In short how to do an apex callout from Class..
Apex class:
*******************************************
global class with sharing ApexCallout{
public void callout()
{
//Construct a HTTP Request
HttpRequest req = new HttpRequest() ;
string strUrl='**********Place your Remote Site Address here**********";
//Before making this callout, you need to add Remote site address in the Remote Site Settings of your Organization..
//Setting Endpoint URL to HTTP request
req.setEndpoint(strUrl);
//Set the request type
req.setMethod('GET');
//HTTP object creation
Http http = new Http();
//Sending the Req throgh HTTPResponse object.
HTTPResponse res = http.send(req);
//System.debug(res.getBody());
//System.debug(res.getStatus());
}
}
If you need to pass some parameters in the method, you can do it..
by changing the method to method with arguments.
You can call this method from trigger also..
Apex class:
*******************************************
global class with sharing ApexCallout{
public void callout()
{
//Construct a HTTP Request
HttpRequest req = new HttpRequest() ;
string strUrl='**********Place your Remote Site Address here**********";
//Before making this callout, you need to add Remote site address in the Remote Site Settings of your Organization..
//Setting Endpoint URL to HTTP request
req.setEndpoint(strUrl);
//Set the request type
req.setMethod('GET');
//HTTP object creation
Http http = new Http();
//Sending the Req throgh HTTPResponse object.
HTTPResponse res = http.send(req);
//System.debug(res.getBody());
//System.debug(res.getStatus());
}
}
If you need to pass some parameters in the method, you can do it..
by changing the method to method with arguments.
You can call this method from trigger also..
Friday, June 1, 2012
GROUP BY - Count Method in Apex Controller
Scenario:
Need to do Totals of Stages in Opportunity for the entire org.
Thought Process:
}
Now create your VF Page to call this and display it whenever the user clicks on this page:
<apex:page controller="TTL_Lesson" action="{!TTL}" showHeader="false" sidebar="false">
<apex:dataTable value="{!queryResults}" var="a" id="theTable" border="2" cellpadding="1" cellspacing="1" bgcolor="#A9D0F5" >
<apex:column >
<apex:facet name="header">Stage</apex:facet>
<apex:outputText value="{!a.OPP}"/>
</apex:column>
<apex:column >
<apex:facet name="header"> Count</apex:facet>
<apex:outputText value="{!a.TTL_Opp}"/>
</apex:column>
</apex:dataTable>
</apex:page>
End result is the image on top
Need to do Totals of Stages in Opportunity for the entire org.
Thought Process:
- What are the columns involved? Answer: StageName and Count or Total
- What methods will we utilize to achieve these results? Answer: Group By SOQL Statement with Count.
- What UI to built this neat logic? Answer: Apex Controller and VisualForce Page
- Need to achieve this type of reporting for the user:
- Use Eclipse IDE or SOQL Explorer to create your SOQL Statement.
SELECT StageName, Count(Name) ce
FROM Opportunity GROUP BY StageName
- Second create Apex Controller name what you like I named it TTL_Lesson, with your logic
//Define your variables public class OppStageHolder { public String OPP {get; set;} public Integer TTL_Opp {get; set;} //Empty Array public OppStageHolder (){} } //Results will be placed within this List public ListqueryResults{ get; set; } //Your Page public PageReference TTL() { AggregateResult[] groupedResults = [SELECT StageName,
Count(Name) ce FROM Opportunity
GROUP BY StageName]; System.Debug('zzavg ' + groupedResults.size()); //Define your List queryResults = new List(); for (AggregateResult ard : groupedResults) { OppStageHolder myObject = new OppStageHolder(); myObject.OPP = String.valueOf(ard.get('StageName')); myObject.TTL_Opp = (Integer) ard.get('ce'); queryResults.add(myObject); } return Page.TTL; }
}
Now create your VF Page to call this and display it whenever the user clicks on this page:
<apex:page controller="TTL_Lesson" action="{!TTL}" showHeader="false" sidebar="false">
<apex:dataTable value="{!queryResults}" var="a" id="theTable" border="2" cellpadding="1" cellspacing="1" bgcolor="#A9D0F5" >
<apex:column >
<apex:facet name="header">Stage</apex:facet>
<apex:outputText value="{!a.OPP}"/>
</apex:column>
<apex:column >
<apex:facet name="header"> Count</apex:facet>
<apex:outputText value="{!a.TTL_Opp}"/>
</apex:column>
</apex:dataTable>
</apex:page>
End result is the image on top
How to use apex variable for total records in Visualforce
Scenario:
I came across a issue where visualforce does not allow one to Count or Sum records in a page.
One solution would be to add more code to the controller to do a count of the records. Which is ok.
A simple solution is to use the apex variable function in Visualforce.
Solution:
public List<Contact> queryResult {get;private set;}
public String qryString {get;set;}
public PageReference query(){
qryString = 'SELECT Name, Email, Phone from Contact';
queryResult = Database.query(qryString);
return null;
}
}
<table width="95%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr height="5">
<td width="35%" class="outsideround_head" align="right">
Total Contacts Returned:
</td>
<td width="8%" class="outside_round_head_value">
<apex:variable var="call" value="{!0}" />
<apex:repeat var="countitall" value="{!queryResult}" >
<apex:variable var="call" value="{!call+1}"/>
</apex:repeat>
<apex:outputText value="{!call}"/>
</td>
</tr>
</table>
</apex:page>
Output: Total Contacts Returned: 10
I came across a issue where visualforce does not allow one to Count or Sum records in a page.
One solution would be to add more code to the controller to do a count of the records. Which is ok.
A simple solution is to use the apex variable function in Visualforce.
Solution:
- Lets do it off Contacts
- In your Apex Controller : Create a SOQL query as is:
public List<Contact> queryResult {get;private set;}
public String qryString {get;set;}
public PageReference query(){
qryString = 'SELECT Name, Email, Phone from Contact';
queryResult = Database.query(qryString);
return null;
}
}
Pretty Simple and Straight Forward.
Now for the VF Page and Magic:
You will see I use the apex variable function to do a couple of things:
create a variable run the query inside that variable counting all the records by 1 within a repeat tag calling the variable with the total Kind of like a for Loop but in Visualforce instead of controller.
<apex:page standardcontroller="Contact" extensions="countcontroller"><table width="95%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr height="5">
<td width="35%" class="outsideround_head" align="right">
Total Contacts Returned:
</td>
<td width="8%" class="outside_round_head_value">
<apex:variable var="call" value="{!0}" />
<apex:repeat var="countitall" value="{!queryResult}" >
<apex:variable var="call" value="{!call+1}"/>
</apex:repeat>
<apex:outputText value="{!call}"/>
</td>
</tr>
</table>
</apex:page>
Output: Total Contacts Returned: 10
Pick list value added dynamically from Controller
Pick list value added dynamically from Controller:
Scenario: We faced issue related with pick list which having some values like ‘abc’,’def’,’ghi’,’jkl’etc. And we have to add another value ‘xyz’ in this pick list on certain condition.
For example we user select open page (visual force page) with Account. Some other user open same page with Opportunity button.
Proposed Solution: We can solve using two ways;
1. Solution: We can do using controller as following code.
Controller:
public List getPauseReason() {
List options = new List();
options.add(new SelectOption('','--None--'));
Schema.DescribeFieldResult fieldResult = Sales_Support_Request__c.Pause_Reason__c.getDescribe();
List ple = fieldResult.getPicklistValues();
for( Schema.PicklistEntry f : ple)
{
options.add(new SelectOption(f.getLabel(), f.getValue()));
}
if(Callfrom=='Account'){
options.add(new SelectOption(‘xyz','xyd'));
}
return options;
}
------------- End of controller-------------
Visual force page:
------------- End of controller-------------
2. Solution: We can do using JavaScript code in Visual force page code as given:
Step1. We have created hidden field which contains where call from like ‘Account’ or ‘Opportunity’.
Step2: We can call this field id in JavaScript code and write condition.
Conclusion: Using this solution we can add value in pick list dynamically in Salesforce.com.
Custom Setting
Custom Setting
Custom Settings is an essentially custom object that is exposed in the applications cache and accessible via their own API. Custom setting will give us to use in SOQL and there is no limit of fields and also use custom settings in formula fields, validation rules, Apex code and the Web Services API.
* Provide advanced application personalization and customization
* Deliver efficient cached data access by user.
How to Create Custom Setting?
Go to Setupà App Set upà Developà Custom Settingà New
Custom Setting Definition Page will open enter the required fields value.
Like Label: OpportunityAction
Object: Opportunity.
Setting Type: List
Visibility: Public
Description: Created for which action.
Setting Type (A List type defines application-level data, such as country codes, that is stored in the application cache. A Hierarchy type defines personalization settings, such as default field values, that can be the overridden at the organization, profile, or user level).
Add New Two Custom Fields this declaration of Oppty fields and related list: Click on New Button
1) Label: API Name
Data Type: Text
Length: 200
2) Label: Object
Data Type: Text
Length: 200
Etc.
Click on Manage Button and enter all fields which you want to in SOQL.
1) Label: Account Name
API Name: AccountId
Object: Opportunity
2) Label: Agents
API Name: Agents__c
Object: Operations_Service__c
Etc.
Apex class Code:
Object Following example is for the fetching the fields from Custom Setting and insert the record.
List<OpportunityAction__c> FieldList =[Select API_Name__c,Object__c fromOpportunityAction__c];
Map<String,Set<String>> objectFieldsList= newMap<String,Set<String>>();
for(OpportunityAction__c field:FieldList){
Set<String> temp= objectFieldsList.get(field.Object__c);
if(temp!=null){
temp.add(field.API_Name__c);
}
else{
temp = new Set<String>();
temp.add(field.API_Name__c);
}
objectFieldsList.put(field.Object__c,temp);
}
//this for loop picks up the API names of all fields against the object OpportunityAction__c in custom setings
for(String OpptyField:objectFieldsList.get(OpportunityAction__c')){
if(OppQuery!=''){
OppQuery=OppQuery+' , ';
}
OppQuery = OppQuery + OpptyField;
}
OppQuery ='Select ' + OppQuery + ' from OpportunityAction__c WHERE Id =\'' + ids + '\' ';
OpportunityAction__c objOppty=Database.query(OppQuery);
insertOpportunity = objOppty.clone(false);
try{
insert insertOpportunity;
}catch(Exception ex){
msg='';
System.debug('Exception 1 : ' +ex);
Database.rollback(sp);
}
Conclusion: As above example we can fetch number of fields in our code and made dynamic SOQL. This feature is very important for our dynamic SOQL and client flexible reqiurment.
Approval Process Code
Technical Issue – User want all new records for an object to be submitted to an Approval Process, however you do not want to the rely on users to manually click the ‘Submit for Approval’ button after creating all the records.
Solution – Create and test necessary Approval Process go through Setup / App Setup / Create / Workflow & Approvals / Approval Processes, implement this simple Apex Trigger (the following example is for the Account object). You will also need to create the test method to ensure code coverage if your current production Apex Classes do not provide adequate coverage also. You can also the add try / catch statements to ensure that the exceptions are caught and handled properly.
Code:
trigger accountApprovalSubmit on Account (after insert) {
// trigger on Account object
for (Account a : trigger.new) {
// to extract all new values on Accounts
Approval.ProcessSubmitRequest app = new Approval.ProcessSubmitRequest();
app.setObjectId(a.id);
//Add the id of account
Approval.ProcessResult result = Approval.process(app);
//pass Approval request in to approval process result set.
}
}
Other Example:
if(Trigger.isAfter)
{
if(Criteria matched)
{
system.debug('condition passed');
Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
req1.setComments('Submitting request for approval.');
req1.setObjectId(Trigger.old[0].Id);
List<id> userId = new List<Id> {userInfo.getUserId()};
req1.setNextApproverIds(userId);
approval.ProcessResult result = Approval.process(req1);
}
Conclusion: Using above code user can insert records without any operation of Submit for Approval Button.
Auto increament Text Area Field Size
Issue – Displaying number of characters remaining on 'Text Area Field' for custom field in the VF Page similar to standard out of box functionality.
Solution – We need java script to implement it.
We are passing id of custom field in function size as first parameter and as second parameter we are passing the size of custom field i.e. In above case we are passing the size as 10000 so at the point of first character it displays message 9999 characters remaining and so on...and it doesn't allow to enter more than 10000 characters, as third parameter we are passing id of div where we need to display message.
Code:
<apex:page standardController="Case">
<script>
function size(fvalue, size, divid) {
var input_field = document.getElementById(fvalue);
var msg_count = document.getElementById(divid);
var char_reamining = '0';
var char_entered = input_field.value.length;
if(char_entered == 0){
msg_count.innerHTML = '';
msg_count.style.background = '#F7F7F7';
}else {
if(char_entered <= size){
char_reamining = size - char_entered;
msg_count.innerHTML = char_reamining+ ' remaining';
msg_count.style.background = 'yellow';
}else{
msg_count.innerHTML = char_reamining + ' remaining';
msg_count.style.background = 'yellow';
input_field.value = input_field.value.substring(0,size);
} } }
</script>
<!—Call the java Script above code in input field-- >
<apex:form >
<div id="msg" class="ErrorMessageClass">
</div>
<apex:inputField value="{!Case.Problem_Descriptions__c}" style="width:900px" onkeyup="javascript:size('{!$Component.formId:pgBlockId:pbs1:tdescription}',10000,'msg');" id="tdescription" />
</apex:form>
</apex:page>
Subscribe to:
Posts (Atom)