About

Edit photo

Showing posts with label apex. Show all posts
Showing posts with label apex. Show all posts

Sunday, June 4, 2017

Salesforce Visualforce Pages Beginner component examples


What is Section Header and how to create? 
     If you are creating a new page and each page needs title and description, can be done by Section Header.

Code:

<apex:page >
    <apex:sectionHeader title="Section1" subtitle="Subtitle1" description="Description1" help="http://google.com" rendered="true"/>
</apex:page>

What is Global Data? how can we use it in VF pages in Salesforce?
     Global data is nothing but accessible in globally. we have many Global variables available in salesforce, refer the link to get all types of Global Variables.

https://help.salesforce.com/articleView?id=dev_understanding_global_variables.htm&language=en_US&type=0

Some Commonly used Global variables are
$User
$Label
$ObjectType
$Organization
$Permission
$Profile
$System
$UserRole

Code:

<apex:page controller="calAge">
    <apex:sectionHeader title="Section1" subtitle="Subtitle1" description="Description1" help="http://google.com" rendered="true"/>

    Lastname: <b>{!$User.LastName}</b> <br/>
    Organization: <b>{!$Organization.Name}</b> <br/>
    Profile: <b>{!$Profile.Name}</b>
    
</apex:page>

How to Parse Data from URL?
     {!$CurrentPage.Parameters.parameterName} is used to get Parameters from URL.
Example, Display Name, Age and Gender from URL in VF page.


Code:
<apex:page>
    <apex:sectionHeader title="Section1" subtitle="Subtitle1" description="Description1" help="http://google.com" rendered="true"/>

    Lastname: <b>{!$User.LastName}</b> <br/>
    Organization: <b>{!$Organization.Name}</b> <br/>
    Profile: <b>{!$Profile.Name}</b>
    
    Parameters from URL: -> {! $CurrentPage.Parameters.Name}, {! $CurrentPage.Parameters.Age}, {! $CurrentPage.Parameters.Gender}
    
</apex:page>

What is Controller in VF page?
     There are two type of controllers in the salesforce, named Standard Controller and Custom Controller.
Standard Controller    :-> StandardController = '<Standard Object Name>'
Custom Controller      :-> Controller = '<Apex class name>'
Extension                    :-> Extension = '<Apex class name>'

Example: Get account name, Note: can't get account name until id parameters parsed in URL.
URL?id=0014100000S6O0s

Code:
<apex:page StandardController="Account">
    <apex:sectionHeader title="Section1" subtitle="Subtitle1" description="Description1" help="http://google.com" rendered="true"/>

    Lastname: <b>{!$User.LastName}</b> <br/>
    Organization: <b>{!$Organization.Name}</b> <br/>
    Profile: <b>{!$Profile.Name}</b><br/><br/>
    
    Account name: {! Account.name}
        
</apex:page>

Example 2: Get list of Account names from Account object.
     It's time to use DataTable, if there are nay repetitive records or list of records, DataTable is required.

<!-- Updated soon-->

What are Output Components in VF page?
Output components are used to display the data, it works just like label in HTML.
OutputLabel  ->   Cannot Edit, Read only
OutputText    ->   Connot Edit, Read only
OutputField   ->   Can Edit, if used InlineEditing option.


Code:

<apex:page StandardController="Account">
    <apex:sectionHeader title="Section1" subtitle="Subtitle1" description="Description1" help="http://google.com" rendered="true"/>

    Lastname: <b>{!$User.LastName}</b> <br/>
    Organization: <b>{!$Organization.Name}</b> <br/>
    Profile: <b>{!$Profile.Name}</b><br/><br/>
    
    <apex:form >
        <apex:inlineEditSupport >
            <apex:outputLabel value="{!account.name}"/>   <br/>
            <apex:outputText value="{!account.name}"/>   <br/>
            <apex:outputField value="{!account.name}"/>   <br/>
        </apex:inlineEditSupport>
    </apex:form>
</apex:page>

What are Input components in VF pages? and example.
     Input components are used to input the values to the object, it is like Textbox in VisualStudio, inputField in HTML.

inputText     -> Used to Input text, irrespective to datatype
inputlabel    -> same as inutText, irrespective to datatype
inputField    -> Same as inputText, respective to Datatype
inputSecret  ->  Password type
inputHidden  -> Hidden Mode

What are Select Components in VF page? and Example.
     Used to select multiple/single (Ex: picklist/Radio/checkbox) value from list of options.
SelectList
SelectOption  -> Options in the picklist are created using this components
SelectOptions  -> When list of options are already available in List datatype.



Code:
VF Page:
<apex:page Controller="calAge1">
    <apex:sectionHeader title="Section1" subtitle="Subtitle1" description="Description1" help="http://google.com" rendered="true"/>

    Lastname: <b>{!$User.LastName}</b> <br/>
    Organization: <b>{!$Organization.Name}</b> <br/>
    Profile: <b>{!$Profile.Name}</b><br/><br/>
    
    <apex:form >
        <apex:selectList size="1">
          <apex:selectOption itemLabel="jan" itemvalue="one"/>
          <apex:selectOption itemLabel="feb" itemvalue="two"/>
          <apex:selectOption itemLabel="mar" itemvalue="three"/>
        </apex:selectList>
        
        <apex:selectList size="1">
          <apex:selectOptions value="{! Method1}"/>
        </apex:selectList>
    </apex:form>
</apex:page>

Apex Custom Controller:
public with sharing class calAge1 {
    public List<SelectOption> getMethod1()
    {
        List<Account> lname = [Select name from account limit 10];
        List<SelectOption> ll = new List<SelectOption>();
        for(integer i=0;i<10;i++)
        {
            ll.add(new selectOption(String.valueOf(i),String.valueOf(lname[i].name)));
        }
        return ll;
    }
}

by
SsaiK

Saturday, March 18, 2017

Scheduling Jobs Simple examples


Example1:

Create a task for the opportunity owners who's opportunity is not closed even close date cross the close date.

Note: Schedule and Batch classes always should be Global.

global class RemindOpptyOwners implements Schedulable {

    global void execute(SchedulableContext ctx) {
        List<Opportunity> opptys = [SELECT Id, Name, OwnerId, CloseDate 
            FROM Opportunity 
            WHERE IsClosed = False AND 
            CloseDate < TODAY];
        // Create a task for each opportunity in the list
        TaskUtils.remindOwners(opptys);
    }
    
}
//Code from Salesforce.com - Trailhead


NoteTaskUtils.remindOwners(opptys); is creates a task for the owners.

Now, Autorun the jobs for every Monday at 2 am.

Schedule jobs run as -> Seconds Minutes Hours DaysOfMonth Month DayOfWeek Year

There are also some special characters you can use:

, used to delimit values [hours, day of month, month, day of week, year]
– used to specify a range [hours, day of month, month, day of week, year]
* used to specify all values [hours, day of month, month, day of week, year]
? used to specify no specific value [day of month, day of week]
/ used to specify increments [hours, day of month, month, day of week, year]
L used to specify the end of a range [day of month, day of week]
W used to specify the nearest weekday [day of month]

# used to specify the nth day of the month [day of week]

RemindOpptyOwners reminder = new RemindOpptyOwners();
// Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
String sch = '0 30 8 10 2 ?';
String jobID = System.schedule('Remind Opp Owners', sch, reminder);


Testing:
http://blog.deadlypenguin.com/blog/2012/05/26/scheduled-actions-in-salesforce-with-apex/

I'll write my own test, Coming soon with real time examples.

Thursday, February 9, 2017

Approval process using apex


An approval process is an automated process which can be used to approve/reject record updates. A record can be submitted for approval request from related list "Approval History". Once a records is submitted it goes for approval to a specified approver. This is a manual process where in every record should be individually sent for approval.
 How about doing this using apex? Sending the record fro approval from trigger? Salesforec provides number of method for handling approval processes in apex.

Let us submit a record for approval process from trigger in an example below.

Lets say you have a approval process named "Account Owner Approval". You can create a approval process by navigating to following:
set up --> create --> approval process





















Trigger to submit a account record for approval if its annual revenue is less then 2000
?
1
2
3
4
5
6
7
8
9
10
trigger Call_AprovalProcess_In_Trigger on Account (before insert, before update) {
 for(Account acc:trigger.new){
    if(acc.AnnualRevenue < 2000){
       approval.ProcessSubmitRequest aprlPrcs = new Approval.ProcessSubmitRequest();     
       aprlPrcs .setComments('Submitting record for approval.');
       aprlPrcs.setObjectId(acc.id);
       approval.ProcessResult result = Approval.process(aprlPrcs);
    }
 }
}

send email in apex salesforce


Salesforce provides method to send emails from apex. We can create a instance of that method, set all the required parameters and then send the emails.

We can set the email addresses to which the email be sent in "setToAddresses", we can give emails seperated by comma. Simialrly bcc,cc email addresses can be seperated by comma . We can specify the body as text or HTMl as desired.

Following is a example wherein emails will be sent to specified addresses upon clicking the button.

Visualforce page <apex:page controller="SendemailController">
 <apex:form >
   <apex:commandButton value="Send Email" action="{!sendEmailFunction}"/>
 </apex:form>
</apex:page>


Controller 
Public with sharing class SendemailController{
   Public SendemailController(){
   }
  
 Public void sendEmailFunction(){
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   String[] toAddresses = new String[] {'testreceipient1@mail.com','testreceipient1@mail.com'}; 
   String[] ccAddresses = new String[] {'testcc1@mail.com','testcc1@mail.com'};
   mail.setToAddresses(toAddresses);
   mail.setCcAddresses(ccAddresses);
   mail.setReplyTo('myemail@mail.com');
   mail.setSenderDisplayName('My Name');
   mail.setSubject('Testing email through apex');
   mail.setBccSender(false);
   mail.setUseSignature(false);
   mail.setPlainTextBody('This is test email body. This mail is being sent from apex code');
   //mail.setHtmlBody('<b> This is HTML body </b>' );
   Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 } 

}

You need to specify the existing correct addresses in the lines marked red in abive code.