All SALES FORCE SCENARIOS
CONTENTS
1.Inserting records into custom object
2.Deleting records of an object using table:
3.Displaying related contact of an account by entering account name in a text box:
4.Detail Page Display Using ActionSupport:
5.Detail page Display using CommandLink:
6.clone the Records using clone() method:
7.Passing values from Javascript to apex class using input hidden:
8.Filtering the Records based on alphabets:
9.Overriding Save functionality:
10.TabPanels with Tabs:
11.Wrapper class for displaying the selected records in Next page:
12.Wrapper class for displaying Int and String Data types :
13.Inserting the records through HTML components:
14.Tabpanels for displaying related lists for specific Account:
15.class for inserting more than one record at a time(list of records):
16.Inserting list of records through For loop:
17.Performing the pagination on VF page (display 2records per page):
18.Dynamic Binding of input fields:
19.Component:
20. outputlink:
21.Display Detail page using commandlinks by passing Ids from VF page to Apex Class:
22.outputlink for navigating vf page to google page:
23.Display the Printable view page using output links:
24.Creating picklist using <apex:selectoption> (this is the static way to place the items with in picklist):
25.Getting all names of an account in to a Picklist
26.Dependent Picklist Preparation using Controller:
27.Reading Data from Text file:
28.Difference between <apex:inputfield> and <apex:outputfield>
29.Placing input fields without using standard controller:
30.Action function to populate the Address Fields:
31.Scheduling Apex:
32.Edit the records using Record Ids:
33.Facets:
34.Listviews:
35.Batch Apex:
36.Dynamic Apex:
37.Retrieving the list of objects from the Org:
38.Retriving the picklist values from the picklist field:
39.Triggers:
40.Account with Multiple Contacts:
41.Trigger.new and Trigger.old:
42.Adding an Error message to a field using Trigger:
43.Map Methods:
44. A Simple class using Map:
45.sObject:
46.Test Classes:
47.Display related contacts using inputfield:-
48.Nested Lists for displaying related contacts:-
i) SENDING eMAIL TO ALL CONTACTS OF AN ACCOUNT:-
Java script & Css
49.Inserting records into custom object with including css:
50.A sample JavaScript:
51.A Sample CSS for changing the Font size:-
52.Sum Calculation using JavaScript Function:
53.CheckBox Hide Or Unhide the components based on Checked Property:
54.Removing the standard css from the pageblock table:
55.showModalDialog():
56.External Javascript:
57.Creating a menu bar:
1. Inserting records into custom object
In this scenario we used custom controller,Apex:inputtext and apex:command Button for inserting records into custom object.
Apex:Page:-
<apex:page sidebar="false" controller="DataLoadTestingClass">
<apex:form >
<div style="border:1px solid; width:200px;">
<div style="height:30px;width:150px;margin-top:20px;margin-left:20px;font-size:15px;color:blue;">
DATALOADTESTING
</div>
<table>
<tr>
<td>
Name
</td>
<td>
<apex:inputtext value="{!nameVal}"/>
</td>
</tr>
<tr>
<td>
City
</td>
<td>
<apex:inputtext value="{!cityVal}" />
</td>
</tr>
<tr>
<td>
Country
</td>
<td>
<apex:inputtext value="{!countryVal}" />
</td>
</tr>
<tr>
<td>
Phone
</td>
<td>
<apex:inputtext value="{!phoneVal}"/>
</td>
</tr>
<tr >
<td colspan="2" align="center">
<apex:commandButton value="INSERT" style="color:red;" action="{!doInsert}" />
</td>
</tr>
</table>
</div>
</apex:form>
</apex:page>
Apex Class:-
public with sharing class DataLoadTestingClass {
public PageReference doInsert() {
DataloadTest__c objdlt = new DataLoadTest__c();
objdlt.name=nameVal;
objdlt.city__c=cityVal;
objdlt.country__c=countryVal;
objdlt.phone__c=phoneVal;
insert objdlt;
pagereference ref = new pagereference('/apex/insertdlttest');
ref.setredirect(true);
return ref;
}
public String phoneVal { get; set; }
public String countryVal { get; set; }
public String cityVal { get; set; }
public String nameVal { get; set; }
}
2.Deleting records of an object using table:
In this scenario we used custom contrller to perform delete action,
and pageblock table to display records and command link to delete individual records.
In this we used 'apex:param' for transmitting individual record ids from vf to apex class.
page:
<apex:page controller="DeleteTestingNew" sidebar="false">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column headerValue="Action">
<apex:commandlink value="Delete" action="{!doDelete}">
<apex:param name="rId" value="{!r.Id}" assignTo="{!rId}"/>
</apex:commandlink>
</apex:column>
<apex:column headerValue="Name">
{!r.name}
</apex:column>
<apex:column headerValue="city">
{!r.City__c}
</apex:column>
<apex:column headerValue="phone">
{!r.Phone__c}
</apex:column>
<apex:column headerValue="country">
{!r.Country__c}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class DeleteTestingNew {
public String rId{get;set;}
DataLoadTest__c delDlt = new DataLoadTest__c();
public PageReference doDelete() {
delDlt=[select Id from DataLoadTest__c where id =:rId];
delete delDlt;
pagereference ref=new pagereference('/apex/newdelete');
ref.setredirect(true);
return ref;
}
List<DataLoadTest__c> lstdlt = new List<DataLoadTest__c>();
public List<DataLoadTest__c> getRecords() {
lstdlt =[select id,name,city__c,country__c,phone__c from DataloadTest__c];
return lstdlt;
}
}
3.Displaying related contact of an account by entering account name in a text box:
This scenario describes the usage of apex:actionstatus. By using apex:actionstatus we can display status message when page is loading. For this we have to use apex:facet along with actionstatus.
Page:
<apex:page sidebar="false" controller="AccWithAllContactsClass">
<apex:form >
<apex:inputtext value="{!accName}" />
<apex:commandButton value="ShowContacts" action="{!showContacts}" rerender="out" status="mystatus"/><br/>
<apex:actionstatus id="mystatus" starttext="please wait it is loading contacts.......">
<apex:facet name="stop">
<apex:outputpanel id="out">
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!conRecords}" var="c">
<apex:column headerValue="Contacts">
{!c.Name}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:outputpanel>
</apex:facet>
</apex:actionstatus>
</apex:form>
</apex:page>
class:
public with sharing class AccWithAllContactsClass {
List<Account> lstaccount = new List<Account>();
List<contact> lstcontacts = new List<contact>();
public List<contact> getConRecords() {
lstcontacts.clear();
accIds.clear();
lstaccount.clear();
system.debug('****AccNameTextValue is *****'+accName);
lstaccount=[select id,name from Account where name=:accName];
for(Integer i=0;i<lstaccount.size();i++)
{
accIds.add(lstaccount[i].Id);
}
lstcontacts =[select id,name,accountId from contact where accountid in : accIds];
system.debug('**** List of Contacts for Test is ***'+lstcontacts);
return lstcontacts;
}
set<string> accIds = new set<string>();
public pagereference showContacts() {
return null;
}
public String accName { get; set; }
}
4.Detail Page Display Using ActionSupport:
This scenario describes the usage of apex:actionsupport and apex:param. Here param is used to pass individual record ids within the vf page to display detail page.
page:
<apex:page sidebar="false" standardController="DataLoadTest__c" recordSetVar="records">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column headerValue="Name">
<apex:actionsupport event="onclick" rerender="out" status="mystatus">
{!r.Name}
<apex:param name="rId" value="{!r.Id}"/>
</apex:actionsupport>
</apex:column>
<apex:column headerValue="City">
{!r.City__c}
</apex:column>
<apex:column headerValue="Country__c">
{!r.Country__c}
</apex:column>
<apex:column headerValue="phone">
{!r.phone__c}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:actionstatus id="mystatus" startText="loading.................">
<apex:facet name="stop">
<apex:outputpanel id="out">
<apex:detail subject="{!$CurrentPage.parameters.rId}" relatedList="false"/>
</apex:outputpanel>
</apex:facet>
</apex:actionstatus>
</apex:form>
</apex:page>
5.Detail page Display using CommandLink:
<apex:page sidebar="false" standardController="DataLoadTest__c" recordSetVar="records">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column headerValue="Name">
<apex:commandLink value="{!r.Name}" rerender="out" status="mystatus">
<apex:param name="rId" value="{!r.Id}"/>
</apex:commandLink>
</apex:column>
<apex:column headerValue="City">
{!r.City__c}
</apex:column>
<apex:column headerValue="Country__c">
{!r.Country__c}
</apex:column>
<apex:column headerValue="phone">
{!r.phone__c}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:actionstatus id="mystatus" startText="loading.................">
<apex:facet name="stop">
<apex:outputpanel id="out">
<apex:detail subject="{!$CurrentPage.parameters.rId}" relatedList="false"/>
</apex:outputpanel>
</apex:facet>
</apex:actionstatus>
</apex:form>
</apex:page>
6.clone the Records using clone() method:
In this scenario we used apex:commandlink and apex:param.
page:
<apex:page sidebar="false" controller="CloneTestingRecordClass">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column headerValue="Name">
{!r.Name}
</apex:column>
<apex:column headerValue="City">
{!r.City__c}
</apex:column>
<apex:column headerValue="Country">
{!r.Country__c}
</apex:column>
<apex:column headerValue="Phone">
{!r.phone__c}
</apex:column>
<apex:column headerValue="Action">
<apex:commandLink value="Clone" action="{!clonedRec}">
<apex:param name="rId" value="{!r.Id}" assignTo="{!rId}"/>
</apex:commandLink>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class CloneTestingRecordClass {
public PageReference clonedRec() {
DataLoadTest__c selectedRecord = [select Id,name,city__c,country__c,phone__c from DataLoadTest__c where id=:rId];
dataLoadtest__c lstnew = selectedRecord.clone(false);
insert lstnew;
pagereference ref = new pagereference('/apex/cloneRecordTesting');
ref.setredirect(true);
return ref;
}
public String rId{get;set;}
List<DataLoadTest__c> lstdlt = new List<DataLoadTest__c>();
public List<DataLoadTest__c> getRecords() {
lstdlt = [select Id,name,city__c,country__c,phone__c from DataloadTest__c];
return lstdlt;
}
}
7.Passing values from Javascript to apex class using input hidden:
to pass values from js to class we have to use a component called <apex:inputhidden>
page:
<apex:page sidebar="false" controller="jstoclassTesting1" id="p1">
<script>
function js(val){
document.getElementById('p1:f1:hdn').value=val;
}
</script>
<apex:form id="f1">
<apex:commandButton value="ClickMe" onclick="js('Welcome')" action="{!showValue}"/>
<apex:inputhidden value="{!hdnValue}" id="hdn"/>
</apex:form>
</apex:page>
class:
public with sharing class jstoclassTesting1 {
public PageReference showValue() {
system.debug('***** showValue is ******'+hdnValue);
return null;
}
public String hdnValue { get; set; }
}
8.Filtering the Records based on alphabets:
In this scenario we used apex:inputhidden and javascript for filtering records.
page1:
<apex:page sidebar="false" id="p1" controller="FilterdataClass">
<style>
.headerRow th{
display:none;
}
</style>
<script>
function showChar(Ch){
document.getElementById('p1:f1:hd').value=Ch;
}
</script>
<apex:form id="f1">
<apex:commandLink value="ALL" onclick="showChar('ALL')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="A" onclick="showChar('A')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="B" onclick="showChar('B')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="C" onclick="showChar('C')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="D" onclick="showChar('D')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="E" onclick="showChar('E')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="F" onclick="showChar('F')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="G" onclick="showChar('G')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="H" onclick="showChar('H')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="I" onclick="showChar('I')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="J" onclick="showChar('J')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="K" onclick="showChar('K')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="L" onclick="showChar('L')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="M" onclick="showChar('M')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="N" onclick="showChar('N')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="O" onclick="showChar('O')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="P" onclick="showChar('P')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="Q" onclick="showChar('Q')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="R" onclick="showChar('R')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="S" onclick="showChar('S')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="T" onclick="showChar('T')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="U" onclick="showChar('U')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="V" onclick="showChar('V')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="W" onclick="showChar('W')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="X" onclick="showChar('X')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="Y" onclick="showChar('Y')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:commandLink value="Z" onclick="showChar('Z')" action="{!showValApex}" reRender="out" status="mystatus"/> |
<apex:inputhidden value="{!hdnVal}" id="hd"/>
<br/>
<apex:actionstatus id="mystatus" startText="loading data.........">
<apex:facet name="stop">
<apex:outputpanel id="out">
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column >
{!r.Name}
</apex:column>
<apex:column >
{!r.City__c}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:outputpanel>
</apex:facet>
</apex:actionstatus>
</apex:form>
</apex:page>
class:
public with sharing class FilterdataClass {
List<Testing__c> lsttest = new List<Testing__c>();
string sQuery='';
public List<Testing__c> getRecords() {
if(hdnVal=='ALL')
{
sQuery='select Id,name,city__c from Testing__c';
}
else
{
sQuery='select Id,name,city__c from Testing__c where name LIKE \''+hdnVal+'%\'';
system.debug('****** sQuery is ******'+sQuery);
}
lsttest = database.query(sQuery);
return lsttest;
}
public PageReference showValApex() {
system.debug('******hdnVal******'+hdnVal);
return null;
}
public String hdnVal { get; set; }
}
9.Overriding Save functionality:
Thi scenario describes how to save records using apex:class.
page:
<apex:page sidebar="false" standardController="Testing__c" extensions="OverrideSAVE">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection columns="1">
<apex:inputfield value="{!Testing__c.Name}"/>
<apex:inputfield value="{!Testing__c.City__c}"/>
<apex:commandButton value="SAVE" action="{!dosave}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class OverrideSAVE {
ApexPages.StandardController con;
public OverrideSAVE(ApexPages.StandardController controller) {
con=controller;
}
public pagereference dosave(){
con.save();
pagereference ref=new pagereference('/apex/standardSavePage');
ref.setredirect(true);
return ref;
}
}
10.TabPanels with Tabs:
In this scenario we used tabpanel for displaying the records of more than one object.
We tabpanel can cotain any number of tabs.
Here we used individual tabs for objects.
page:
<apex:page sidebar="false" controller="DisplayDataTestxyz">
<apex:form >
<apex:tabpanel >
<apex:tab label="Testing Data">
<!-- Logic for displaying the Accounts Data -->
<apex:pageblock >
<apex:pageblocksection >
<apex:pageblocktable value="{!testingrecords}" var="tr">
<apex:column headerValue="Name">
{!tr.Name}
</apex:column>
<apex:column headerValue="City">
{!tr.City__c}
</apex:column>
</apex:pageblocktable>
</apex:pageblocksection>
</apex:pageblock>
</apex:tab>
<apex:tab label="DataLoadTest Data">
<!-- Logic for Displaying the Conthttps://c.ap1.visual.force.com/apex/tabpanelsacts Data -->
<apex:pageblock >
<apex:pageblocksection >
<apex:pageblocktable value="{!dataloadtestrecords}" var="dr">
<apex:column headerValue="Name">
{!dr.Name}
</apex:column>
<apex:column headerValue="City">
{!dr.City__c}
</apex:column>
<apex:column headerValue="Country">
{!dr.City__c}
</apex:column>
<apex:column headerValue="Phone">
{!dr.phone__c}
</apex:column>
</apex:pageblocktable>
</apex:pageblocksection>
</apex:pageblock>
</apex:tab>
</apex:tabpanel>
</apex:form>
</apex:page>
class:
public with sharing class DisplayDataTestxyz {
List<DataLoadTest__c> lstdlt = new List<DataLoadTest__c>();
public List<DataLoadTest__c> getDataloadtestrecords() {
lstdlt=[select Id,name,city__c,country__c,phone__c from DataLoadTest__c];
return lstdlt;
}
List<Testing__c> lsttesting = new List<Testing__c>();
public List<Testing__c> getTestingrecords() {
lsttesting=[select Id,name,city__c from Testing__c];
return lsttesting;
}
}
11.Wrapper class for displaying the selected records in Next page:
This scenario mainly describes the usage of Wrapper class.
Wrapper class is used to diaplay different types of datatypes in a single table.
In the following scenario we are displaying boolean and list datatypes.
page1:
<apex:page sidebar="false" controller="WrapTestClass">
<apex:form >
<apex:pageblock >
<apex:pageblocksection >
<apex:pageblocktable value="{!testingrecords}" var="tr">
<apex:column headervalue="Action">
<apex:inputcheckbox value="{!tr.ischecked}"/>
</apex:column>
<apex:column headerValue="Name">
{!tr.TName}
</apex:column>
<apex:column headerValue="City">
{!tr.TCity}
</apex:column>
</apex:pageblocktable>
</apex:pageblocksection>
</apex:pageblock>
<apex:commandButton value="SELECT" action="{!selRecDisplay}"/>
</apex:form>
</apex:page>
class1:
public with sharing class WrapTestClass {
List<string> lstselectedNames = new List<string>();
public PageReference selRecDisplay() {
for(wrapper w: lstwrap){
if(w.ischecked==true){
lstselectedNames.add(w.Tname);
}
}
List<Testing__c> lstselectedrecords = [select Id,name,city__c from Testing__c where name in : lstselectedNames];
List<String> lstselectedRecordIds = new List<String>();
for(Integer i=0;i<lstselectedrecords.size();i++){
lstselectedRecordIds.add(lstselectedrecords[i].Id);
}
string s='';
for(Integer i=0;i<lstselectedRecordIds.size();i++)
{
if(i<lstselectedRecordIds.size()-1)
s=s+lstselectedRecordIds[i]+':';
else
s=s+lstselectedRecordIds[i];
}
pagereference ref = new pagereference('/apex/t123?value='+s);
ref.setredirect(true);
return ref;
}
List<wrapper> lstwrap = new List<wrapper>();
List<Testing__c> lsttest = new List<Testing__c>();
public List<wrapper> getTestingrecords() {
lsttest = [select Id,name,city__c from Testing__c];
for(Integer i=0;i<lsttest.size();i++)
{
lstwrap.add(new wrapper(lsttest[i].name,lsttest[i].city__c));
}
return lstwrap;
}
public class wrapper{
public String Tname{get;set;}
public String Tcity{get;set;}
public boolean ischecked{get;set;}
public wrapper(String Tname,String Tcity)
{
this.Tname=Tname;
this.Tcity=Tcity;
this.ischecked=false;
}
}
}
page2:
<apex:page controller="DClass">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column headerValue="Name">
{!r.Name}
</apex:column>
<apex:column headerValue="City">
{!r.City__c}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class2:
public with sharing class DClass {
List<Testing__c> lsttest = new List<Testing__c>();
public List<Testing__c> getRecords() {
List<String> ids = url.split(':');
lsttest = [select Id,name,city__c from Testing__c where id in : ids];
return lsttest;
}
String url = apexpages.currentpage().getparameters().get('value');
}
12.Wrapper class for displaying Int and String Data types :
page:
<apex:page sidebar="false" controller="WrapperIntStringDisplayClassTest">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!lstwrapperIntString}" var="w">
<apex:column headervalue="Action">
<apex:inputcheckbox />
</apex:column>
<apex:column headervalue="TestingName">
{!w.Tname}
</apex:column>
<apex:column headerValue="TestingCity">
{!w.Tcity}
</apex:column>
<apex:column headervalue="DataLoadCountry">
{!w.Dcountry}
</apex:column>
<apex:column headerValue="DataLoadPhone">
{!w.Dphone}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class WrapperIntStringDisplayClassTest {
List<Testing__c> lsttest = new List<Testing__c>();
List<DataLoadTest__c> lstdlt = new List<DataLoadTest__c>();
public List<wrapper> lstw = new List<wrapper>();
public List<wrapper> getLstwrapperIntString() {
lsttest = [select name,city__c from Testing__c];
lstdlt = [select country__c,phone__c from DataLoadTest__c];
for(Integer i=0;i<lstdlt.size();i++){
lstw.add(new wrapper(lsttest[i].name,lsttest[i].city__c,lstdlt[i].country__c,lstdlt[i].phone__c));
}
return lstw;
}
public class wrapper{
public String Tname{get;set;}
public String Tcity{get;set;}
public String Dcountry{get;set;}
public String Dphone{get;set;}
public wrapper(String Tname,String Tcity,String Dcountry,String Dphone){
this.Tname=Tname;
this.Tcity=Tcity;
this.Dcountry=Dcountry;
this.Dphone=Dphone;
}
}
}
13.Inserting the records through HTML components:
This scenario describes how to insert records through HTML components.
page:
<apex:page sidebar="false" controller="HTMLCONTest">
<apex:form >
Name: <input type="text" name="txt1"/> <br/>
city: <input type="text" name="txt2"/> <br/>
Country : <input type ="txt" name="txt3"/><br/>
Phone : <input type="text" name="txt4"/><br/>
<apex:commandButton value="INSERT" action="{!doSave}"/>
</apex:form>
</apex:page>
class:
public with sharing class HTMLCONTest {
public PageReference doSave() {
DataLoadTest__c objDlt = new DataLoadTest__c();
objDlt.Name = apexpages.currentpage().getparameters().get('txt1');
objDlt.city__c= apexpages.currentpage().getparameters().get('txt2');
objDlt.country__c= apexpages.currentpage().getparameters().get('txt3');
objDlt.phone__c= apexpages.currentpage().getparameters().get('txt4');
insert objDlt;
return null;
}
}
14.Tabpanels for displaying related lists for specific Account:
In this scenario we used two pages, one for displaying all accounts and another for displaying individual contacts, opportunities and cases for a perticular account.
In second page we used tabpanel for dispalying contacts,cases and opportunities.
page1:
<apex:page sidebar="false" controller="RelatedListClass">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!accRecords}" var="acc">
<apex:column >
<apex:commandLink value="{!acc.Name}" action="{!passingId}">
<apex:param name="accId" value="{!acc.Id}" assignTo="{!accId}"/>
</apex:commandLink>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class1:
public with sharing class RelatedListClass {
public PageReference passingId() {
pagereference ref = new pagereference('/apex/relatedlistdatadisplaypage?value='+accId);
ref.setredirect(true);
return ref;
}
List<Account> lstaccounts = new List<Account>();
public List<Account> getAccRecords() {
lstaccounts = [select Id,name from Account];
return lstaccounts;
}
public String accId{get;set;}
}
page2:
<apex:page controller="RelatedListDataDisplayClass" sidebar="false">
<apex:form >
<apex:tabpanel >
<apex:tab label="Contacts">
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!conRecords}" var="con">
<apex:column >
{!con.Name}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:tab>
<apex:tab label="Opportunities">
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!oPPRecords}" var="opp">
<apex:column >
{!opp.Name}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:tab>
<apex:tab label="Cases">
<apex:pagemessages ></apex:pagemessages>
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!caseRecords}" var="c">
<apex:column >
{!c.caseNumber}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:tab>
</apex:tabpanel>
</apex:form>
</apex:page>
class2:
public with sharing class RelatedListDataDisplayClass {
List<case> lstcase = new List<case>();
public List<case> getCaseRecords() {
lstcase = [select Id,caseNumber,AccountId from case where AccountId = : aId];
if(lstcase.size()==0)
{
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.WARNING, 'Case List Doest not contains any records');
ApexPages.addMessage(myMsg);
}
return lstcase;
}
List<opportunity> lstopp = new List<opportunity>();
public List<opportunity> getOPPRecords() {
lstopp=[select Id,name,AccountId from opportunity where AccountId =: aId];
return lstopp;
}
List<contact> lstcontacts = new List<contact>();
public list<contact> getConRecords() {
lstcontacts=[select Id,name,AccountId from Contact where AccountId =: aId];
return lstcontacts;
}
String aId = apexpages.currentpage().getparameters().get('value');
}
15.class for inserting more than one record at a time (list of records)
public class insert100
{
public void m1()
{
List<Testing__c> lstTesting = new List<Testing__c>();
Testing__c objTest;
objTest = new Testing__c(name='Testing1',city__c='City1');
lstTesting.add(objTest);
objTest = new Testing__c(name='Testing2',city__c='City2');
lstTesting.add(objTest);
objTest = new Testing__c(name='Testing3',city__c='City3');
lstTesting.add(objTest);
objTest = new Testing__c(name='Testing4',city__c='City4');
lstTesting.add(objTest);
objTest = new Testing__c(name='Testing5',city__c='City5');
lstTesting.add(objTest);
insert lstTesting;
}
}
* In order to execute above class , go to System Log and execute as follows
insert100 obj=new insert100();
obj.m1();
16.Inserting list of records through For loop:
public class insert100
{
public void m1()
{
List<Testing__c> lstTesting = new List<Testing__c>();
Testing__c objTest;
for(Integer i=6;i<=100;i++)
{
objTest=new Testing__c(name='Testing'+string.valueof(i),city__c='City'+string.valueof(i));
lstTesting.add(objTest);
}
insert lstTesting;
}
}
* In order to execute above class , go to System Log and execute as follows
insert100 obj=new insert100();
obj.m1();
17.Performing the pagination on VF page (display 2 records per page)
page:
<apex:page sidebar="false" standardController="Testing__c" recordSetVar="records" extensions="PageDataClass">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column headerValue="Name">
{!r.Name}
</apex:column>
<apex:column headerValue="City">
{!r.City__c}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
<apex:commandLink value="previous" action="{!previous}"/> |
<apex:commandLink value="next" action="{!next}"/>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class PageDataClass {
public PageDataClass(ApexPages.StandardSetController controller) {
controller.setpagesize(2);
}
}
18.Dynamic Binding of input fields:
In scenario we used apex:repeat to get all inputfields dynamically.
page:
<apex:page sidebar="false" standardController="Testing__c" extensions="DynamicBindingFieldsOnVFPage">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection columns="1">
<apex:repeat value="{!fields}" var="f">
<apex:inputfield value="{!Testing__c[f]}"/>
</apex:repeat>
</apex:pageBlockSection>
<apex:commandButton value="Insert" action="{!doSave}"/>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class DynamicBindingFieldsOnVFPage {
public DynamicBindingFieldsOnVFPage(ApexPages.StandardController controller) {
}
public pagereference dosave()
{
return null;
}
public List<String> lstfields = new List<String>();
public List<String> getfields(){
lstfields.add('Name');
lstfields.add('city__c');
return lstfields;
}
}
19.Component:
code for component:-
<apex:component >
<apex:form >
<apex:outputtext value="Welcome To Hyderabad" style="color:blue;font-size:30px;">
</apex:outputtext>
</apex:form>
</apex:component>
calling VF component:
/apexcomponent/componentName
page:
<apex:page sidebar="false" standardController="Testing__c" extensions="DynamicBindingFieldsOnVFPage">
<c:co1 />
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection columns="1">
<apex:repeat value="{!fields}" var="f">
<apex:inputfield value="{!Testing__c[f]}"/>
</apex:repeat>
</apex:pageBlockSection>
<apex:commandButton value="Insert" action="{!doSave}"/>
</apex:pageBlock>
</apex:form>
<c:co1 />
</apex:page>
class:
public with sharing class DynamicBindingFieldsOnVFPage {
public DynamicBindingFieldsOnVFPage(ApexPages.StandardController controller) {
}
public pagereference dosave()
{
return null;
}
public List<String> lstfields = new List<String>();
public List<String> getfields(){
lstfields.add('Name');
lstfields.add('city__c');
return lstfields;
}
}
20. outputlink:
display the detail page of a record when click on it.
page:
<apex:page sidebar="false" standardController="DataLoadTest__c" recordSetVar="records">
<style>
.headerRow th
{
display:none;
}
</style>
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column >
<apex:outputlink value="https://ap1.salesforce.com/{!r.Id}">{!r.Name}</apex:outputlink>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
21.Display Detail page using commandlinks by passing Ids from VF page to Apex Class
page:
<apex:page sidebar="false" controller="Detailoutputlink1">
<style>
.headerRow th
{
display:none;
}
</style>
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column >
<apex:commandLink value="{!r.Name}" action="{!showDetail}">
<apex:param name="rId" value="{!r.Id}" assignTo="{!rId}"/>
</apex:commandLink>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class Detailoutputlink1 {
public String rId{get;set;}
public PageReference showDetail() {
pagereference ref = new pagereference('https://ap1.salesforce.com/'+rId);
ref.setredirect(true);
return ref;
}
List<DataLoadTest__c> lstdlt = new List<DataLoadTest__c>();
public List<DataLoadTest__c> getRecords() {
lstdlt=[select Id,name from DataLoadTest__c];
return lstdlt;
}
}
22.outputlink for navigating vf page to google page...
<apex:page sidebar="false" >
<apex:form >
<apex:outputlink value="http://www.google.co.in/">Google</apex:outputlink>
</apex:form>
</apex:page>
23.Display the Printable view page using output links:
page:
<apex:page sidebar="false" standardController="DataLoadTest__c" recordSetVar="records">
<style>
.headerRow th
{
display:none;
}
</style>
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column >
<apex:outputlink value="https://ap1.salesforce.com/{!r.Id}/p?retURL=/{!r.Id}">{!r.Name}</apex:outputlink>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
24.Creating picklist using <apex:selectoption> (this is the static way to place the items with in picklist)
page:
<apex:page sidebar="false" >
<apex:form >
Countries: <apex:selectList multiselect="false" size="1">
<apex:selectoption itemvalue="--None--" itemlabel="--None--"></apex:selectoption>
<apex:selectoption itemvalue="India" itemlabel="India"></apex:selectoption>
<apex:selectoption itemvalue="Australia" itemlabel="Australia"></apex:selectoption>
<apex:selectoption itemvalue="America" itemlabel="America"></apex:selectoption>
</apex:selectList>
</apex:form>
</apex:page>
25.Getting all names of an account in to a Picklist
page:
<apex:page sidebar="false" controller="accPickNamesDisplayClass">
<apex:form >
<apex:selectList multiselect="false" size="1">
<apex:selectOptions value="{!accNames}">
</apex:selectOptions>
</apex:selectList>
</apex:form>
</apex:page>
class:
public with sharing class accPickNamesDisplayClass {
List<selectOption> options = new List<selectOption>();
public List<selectOption> getAccNames() {
for(DataLoadTest__c acc : [select Id,name from DataLoadTest__c])
{
options.add(new selectOption(acc.name,acc.name));
}
return options;
}
}
26.Dependent Picklist Preparation using Controller:
In this scenario we can see how to generate a picklist dynamically and preparation of dependant picklists.
Here dependant picklist is will be populated using apex:actionsupport.
page:
<apex:page sidebar="false" controller="DependentClassabcd">
<apex:form >
Departments: <apex:selectList value="{!selDept}" multiselect="false" size="1">
<apex:actionSupport event="onchange" reRender="out"/>
<apex:selectOptions value="{!deptnames}">
</apex:selectOptions>
</apex:selectList> <br/>
Employees: <apex:selectList multiselect="false" id="out" size="1">
<apex:selectOptions value="{!empnames}">
</apex:selectOptions>
</apex:selectList>
</apex:form>
</apex:page>
class:
public with sharing class DependentClassabcd {
public String selDept { get; set; }
List<selectOption> empOptions = new List<selectOption>();
public List<selectOption> getEmpnames() {
empOptions.clear();
empOptions.add(new selectOption('--None--','--None--'));
for(Employee__c objEmp : [select Id,name,department__c from Employee__c where department__r.name=:selDept]){
empOptions.add(new selectOption(objEmp.name,objEmp.name));
}
return empOptions;
}
List<selectOption> deptOptions = new List<selectOption>();
public List<selectOption> getDeptnames() {
deptOptions.add(new selectOption('--None--','--None--'));
for(Department__c objDept : [select name from Department__c]){
deptOptions.add(new selectOption(objDept.name,objDept.name));
}
return deptOptions;
}
}
27.Reading Data from Text file:
This scenario is for inserting a file of email ids at a time by reading from a textfile.
Here we used apex:inputfile for uploading a file.
In this scenario all the email ids of textfile must be separated by comma.
page:
<apex:page sidebar="false" controller="FileReadingClassxxx">
<apex:form >
<apex:inputfile value="{!fileBody}"/>
<apex:commandButton value="ReadDataIntoMyObject" action="{!readContent}"/>
</apex:form>
</apex:page>
class:
public with sharing class FileReadingClassxxx {
String fileContent='';
public PageReference readContent() {
fileContent = fileBody.toString();
List<string> allemails = fileContent.split(',');
EmailSpace__c myemail = new EmailSpace__c();
List<EmailSpace__c> lstemails = new List<EmailSpace__c>();
for(Integer i=0;i<allemails.size();i++)
{
myemail = new EmailSpace__c(name=allemails[i]);
lstemails.add(myemail);
}
insert lstemails;
return null;
}
public blob fileBody { get; set; }
}
28.Difference between <apex:inputfield> and <apex:outputfield>
<apex:page sidebar="false" standardController="account">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:outputfield value="{!account.name}"> </apex:outputfield>
<apex:inputfield value="{!account.phone}"></apex:inputfield>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
29.Placing input fields without using standard controller:
TO place any input field you have to create a property for that object in apex class.
So that you can use that property name with in input field to place the input component.
page:
<apex:page Controller="ContactClass" sidebar="false">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:inputfield value="{!con1.lastname}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class ContactClass {
public Contact con1{get;set;}
}
30.Action function to populate the Address Fields:
In this scenario whenever we select an account from a contact
automatically the address fields are copied from account to contact.
page:
<apex:page standardController="Contact" extensions="ContactClass" sidebar="false">
<apex:form >
<apex:actionFunction name="populatefields" action="{!dopop}"/>
<apex:pageBlock >
<apex:pageBlockSection columns="1">
<apex:inputfield value="{!con1.AccountId}" onchange="populatefields()"/>
<apex:inputfield value="{!con1.Mailingcity}"/>
<apex:inputfield value="{!con1.Mailingcountry}"/>
<apex:inputfield value="{!con1.Mailingpostalcode}"/>
<apex:inputfield value="{!con1.Mailingstate}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class ContactClass {
public ContactClass(ApexPages.StandardController controller) {
con1 =(contact)controller.getRecord();
}
public PageReference dopop() {
Account objAcc =[select Id,name,Billingcity,Billingcountry,billingstate,billingpostalcode from Account where Id =:con1.AccountId ];
con1.Mailingcity=objAcc.billingcity;
con1.mailingcountry = objAcc.billingcountry;
con1.mailingpostalcode = objAcc.billingpostalcode;
con1.mailingstate = objAcc.billingstate;
return null;
}
public Contact con1{get;set;}
}
31.Scheduling Apex:
In order to execute a process at specific time intervals we use scheduling apex in salesforce.
system log code:
XYZTest m = new XYZTest();
String sch = '1 22 9 29 11 ? '; // sec,min,hours,day,week,month,year(optional)
system.schedule('Merge Job123', sch, m);
class code:
global class XYZTest implements schedulable
{
global void execute(SchedulableContext sc)
{
Testing__c objTest = new Testing__c();
objTest.name='ScheduleRecordxxxxxxxxxxxxxxxxxName';
objTest.city__c='ScheduleRecord1City';
insert objTest;
}
}
32.Edit the records using Record Ids:
Here we can directly navigate to the standard Edit page using record IDs.
page:
<apex:page sidebar="false" standardController="Department__c" recordSetVar="records" extensions="EditDataClass">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column >
<apex:commandlink value="{!r.Name}" action="{!editdata}">
<apex:param name="rId" value="{!r.Id}" assignTo="{!rId}"/>
</apex:commandlink>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class EditDataClass {
public EditDataClass(ApexPages.StandardSetController controller) {
}
public String rId{get;set;}
public pagereference editdata()
{
pagereference ref = new pagereference('https://ap1.salesforce.com/'+rId+'/e?retURL=%2F'+rId);
ref.setredirect(true);
return ref;
// return (new pagereference('https://ap1.salesforce.com/'+rId+'/e?retURL=%2F'+rId).setredirect(true));
}
}
33.Facets:
To set both header value and footer value for a table.
page:
<apex:page sidebar="false" standardController="Department__c" recordSetVar="records" extensions="EditDataClass">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column >
<apex:facet name="header">NAME</apex:facet>
<apex:facet name="footer">NAME FOR Department</apex:facet>
<apex:commandlink value="{!r.Name}" action="{!editdata}">
<apex:param name="rId" value="{!r.Id}" assignTo="{!rId}"/>
</apex:commandlink>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class EditDataClass {
public EditDataClass(ApexPages.StandardSetController controller) {
}
public String rId{get;set;}
public pagereference editdata()
{
pagereference ref = new pagereference('https://ap1.salesforce.com/'+rId+'/e?retURL=%2F'+rId);
ref.setredirect(true);
return ref;
// return (new pagereference('https://ap1.salesforce.com/'+rId+'/e?retURL=%2F'+rId).setredirect(true));
}
}
34.Listviews:
<apex:page sidebar="false" controller="Listviewclass">
<apex:form >
Enter Dept: <apex:inputtext value="{!deptname}"/>
<apex:commandButton value="SAVE" action="{!dosave}"/>
</apex:form>
<apex:listViews type="Department__c"/>
</apex:page>
class:
public with sharing class Listviewclass {
public PageReference dosave() {
Department__c objDept = new Department__c();
objDept.name=deptname;
insert objDept;
return null;
}
public String deptname { get; set; }
}
35.Batch Apex:
============
syntax:
global class BATCHTEST1 implements Database.batchable<sobject>
{
global database.queryLocator start(database.batchableContext bc)
{
return database.getQuerylocator(query);
}
global void execute(database.batchablecontext bc,List<urObjName> variable)
{
// logic to proceed
}
global void finish(database.batchalecontext bc)
{
// logic for your confirmation
}
}
ex:
global class BATCHTESTxyz implements Database.batchable<sobject>
{
global database.queryLocator start(database.batchableContext bc)
{
return database.getQuerylocator('select Id,name from TriggerTest__c ');
}
global void execute(database.batchablecontext bc,List<TriggerTest__c> lstTrigger)
{
for(Integer i=0;i<lstTrigger.size();i++)
{
if(lstTrigger[i].name='Tst')
{
lstTrigger[i].name='Testing';
}
}
update lstTrigger;
}
global void finish(database.batchalecontext bc)
{
system.debug('****** Records Update Successfully');
}
system log:
1)
BATCHTESTXYZ obj = new BATCHTESTXYZ();
database.executebatch(obj);
=======
2)
database.executebatch(new BATCHTESTXYZ());
36.Dynamic Apex:
Retrieving all fields from a custom object / standard object:
page:
<apex:page sidebar="false" standardController="DataLoadTest__c" extensions="DDisplayFields">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection columns="1">
<apex:repeat value="{!fields}" var="f">
<apex:inputfield value="{!DataLoadTest__c[f]}"/>
</apex:repeat>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class DDisplayFields {
public DDisplayFields(ApexPages.StandardController controller) {
}
// List<String> lstfields = new List<string>();
public List<string> getfields()
{
map<String, Schema.SObjectType> m1 = Schema.getGlobalDescribe() ;
SObjectType objToken1 = m1.get('DataLoadTest__c');
DescribeSObjectResult objDef1= objToken1.getDescribe();
map<String, SObjectField> fieldmap = objDef1.fields.getmap();
List<String> lstobjectfields1= new List<String>();
List<String> fieldLabels1= new List<String>();
map<String,String> fieldLabelNamemap1= new map<String,String>();
for (String fName1:fieldmap.keySet())
{
if(fieldmap.get(fName1).getDescribe().getType()!=Schema.DisplayType.Time &&
fieldmap.get(fName1).getDescribe().getType()!=Schema.DisplayType.anytype&&
fieldmap.get(fName1).getDescribe().getType()!=Schema.DisplayType.base64 &&
fieldmap.get(fName1).getDescribe().getType()!=Schema.DisplayType.EncryptedString &&
fieldmap.get(fName1).getDescribe().getType()!=Schema.DisplayType.Id &&
fieldmap.get(fName1).getDescribe().getType()!=Schema.DisplayType.multiPicklist &&
fieldmap.get(fName1).getDescribe().getType()!=Schema.DisplayType.Reference &&
fieldmap.get(fName1).getDescribe().getType()!=Schema.DisplayType.TextArea)
{
fieldLabels1.add(fieldmap.get(fName1).getDescribe().getLabel());
fieldLabelNamemap1.put(fieldmap.get(fName1).getDescribe().getLabel(), fName1);
}
}
for (String fLabel1:fieldLabels1){
if(flabel1 !='Created Date'&& flabel1!='Last Activity Date' && flabel1!='Last modified Date' && flabel1!='Deleted' && flabel1!='System modstamp'&& flabel1!='')
{
//lstobjectfields.add(new selectOption(fieldLabelNamemap.get(flabel),fLabel));
lstobjectfields1.add(fieldLabelNamemap1.get(flabel1));
}
}
system.debug('#### All Fields are ####'+lstobjectfields1);
return lstobjectfields1;
}
}
37.Retrieving the list of objects from the Org:
page:
<apex:page sidebar="false" controller="DObjDisplay">
<apex:form >
ObjectNames:
<apex:selectlist multiselect="false" size="1">
<apex:selectOptions value="{!objNames}">
</apex:selectOptions>
</apex:selectlist>
</apex:form>
</apex:page>
class:
public with sharing class DObjDisplay {
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
public List<SelectOption> getobjNames()
{
List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
List<SelectOption> options = new List<SelectOption>();
for(Schema.SObjectType f : gd)
{
options.add(new SelectOption(f.getDescribe().getName(),f.getDescribe().getName()));
}
return options;
}
}
38.Retriving the picklist values from the picklist field:
page:
<apex:page sidebar="false" controller="Dpicklist">
<apex:form >
Country:
<apex:selectlist multiselect="false" size="1">
<apex:selectoptions value="{!countrynames}">
</apex:selectoptions>
</apex:selectlist>
</apex:form>
</apex:page>
class:
public with sharing class Dpicklist {
public List<SelectOption> getcountrynames()
{
set<String> setobj = new set<string>();
List<SelectOption> options = new List<SelectOption>();
Schema.DescribeFieldResult ccity = Schema.sObjectType.Testing__c.fields.country__c.getSObjectField().getDescribe();
options.add(new selectoption('--None--','--None--'));
for(PicklistEntry ent:ccity.getpicklistvalues())
{
options .add(new SelectOption(ent.getValue(), ent.getLabel()));
setobj.add(ent.getvalue());
}
return options;
}
}
39.Triggers:
trigger trigEventsTest on Department__c (before insert,after insert,before update,after update) {
if(Trigger.isInsert)
{
system.debug('***IsINSERT*****');
}
if(Trigger.isUpdate)
{
system.debug('******IsUpdate*****');
}
if(Trigger.isBefore && Trigger.isInsert)
{
system.debug('****IsBefore and IsInsert*****');
}
if(Trigger.isAfter && Trigger.isInsert)
{
system.debug('*******IsAfter and IsInsert*****');
}
if(Trigger.isBefore && Trigger.isUpdate)
{
system.debug('*****Before Update******');
}
}
40.Account with Multiple Contacts:
trigger Con5Insert on Account (after insert) {
if(Trigger.isAfter)
{
system.debug('****New Account Record is ******'+Trigger.new);
Contact objContact ;
List<Contact> lstcon = new List<Contact>();
for(Integer i=1;i<=5;i++)
{
objContact = new Contact(lastname='AAAAAAAAA'+string.valueof(i),AccountId=Trigger.new[0].Id);
lstcon.add(objContact);
}
system.debug('****List Of Contacts *****'+lstcon.size());
insert lstCon;
}
}
41.Trigger.new and Trigger.old
trigger trigEventsTest on Department__c (before update,after update) {
If(Trigger.new[0].name != Trigger.new[0].name)
{
system.debug('*****Value Changed******');
}
else
{
system.debug('*****Value did not change******');
}
}
42. Add Error:
trigger trigEventsTest on Department__c (before insert) {
if(Trigger.new[0].name=='India')
{
Trigger.new[0].name.addError('Name should not be India');
}
}
43.Map Methods:
public class MapTesting
{
public void m1()
{
map<Integer,String> m1 = new map<Integer,String>{1=>'One',2=>'Two'};
system.debug('*******Map is *********'+m1);
// get() : to get the value from the specific key..
String s = m1.get(2);
system.debug('******Second Key value is ****'+s);
// put() : put the value at specific key.
m1.put(3,'Three');
system.debug('****** Now new map is ******'+m1);
// size() : Returns the size of the map (it returns an integer)
Integer x = m1.size();
system.debug('****** Map size is *****'+x);
// clone() : copies the map values into another map..
map<Integer,String> m2 = m1.clone();
system.debug('***** After cloning m2 map is *****'+m2);
// keyset() : Returns all the key values from the existing map.
set<Integer> keys = m1.keyset();
system.debug('****All keys in M1 map is ****'+keys);
List<String> lstvalues = m1.values();
system.debug('*******all Values are *****'+lstvalues);
boolean result = m1.isEmpty();
system.debug('***** Result is *****'+result);
m1.remove(3);
system.debug('******* After Removing Map Value is ******'+m1);
m1.clear();
system.debug('**** Afer clear map is *****'+m1);
system.debug('***** After Clearing all Values ******'+m1.isEmpty());
}
}
system log:
mapTesting mObj = new mapTesting();
mObj.m1();
44. A Simple class using Map;
public class MapTesting
{
public void m1()
{
map<Id,Department__c> m1 = new map<Id,Department__c>([select Id,name from Department__c]);
List<String> lstnames = new List<String>();
for(Id ids : m1.keyset())
{
lstnames.add(m1.get(ids).name);
}
system.debug('*********all Names are *****'+lstnames);
}
}
mapTesting mObj = new mapTesting();
mObj.m1();
45.sObjects:
public class MapTesting
{
public void m1()
{
List<Department__c> lstRecords = [select Id,name from Department__c];
system.debug('***** lstRecords *******'+lstRecords);
List<String> lstnames = new List<String>();
for(sObject sobj : lstRecords)
{
lstnames.add(string.valueof(sobj.get('name')));
}
system.debug('******AllNames ******'+lstnames);
}
}
46.TestClasses:
Syntax:
@istest
private class TestclassName
{
public static testmethod void testmethodname()
{
// logic to cover the all methods in source class
}
}
Normalclass:
============
public class NormalXYZ
{
public void m1()
{
integer i=10,j=20;
system.debug('******Total value is *****'+(i+j));
}
public void m2()
{
integer i=10,j=20;
system.debug('******Multiplication is *****'+(i*j));
}
}
TestClass:
==========
@isTest
private class TestNormalXYZ
{
public static testmethod void testm1()
{
NormalXYZ objNormal = new NormalXYZ();
objNormal.m1();
objNormal.m2();
}
}
============================================================
Ex2:
public with sharing class AccWithAllContactsClass {
List<Account> lstaccount = new List<Account>();
List<contact> lstcontacts = new List<contact>();
public List<contact> getConRecords() {
lstcontacts.clear();
accIds.clear();
lstaccount.clear();
system.debug('****AccNameTextValue is *****'+accName);
lstaccount=[select id,name from Account where name=:accName];
for(Integer i=0;i<lstaccount.size();i++)
{
accIds.add(lstaccount[i].Id);
}
lstcontacts =[select id,name,accountId from contact where accountid in : accIds];
system.debug('**** List of Contacts for Test is ***'+lstcontacts);
return lstcontacts;
}
set<string> accIds = new set<string>();
public pagereference showContacts() {
return null;
}
public String accName { get; set; }
public static testmethod void testm1()
{
AccWithAllContactsClass obj = new AccWithAllContactsClass ();
Account accobj = new account(name='TestAcc');
insert accobj;
obj.accName=accobj.name;
obj.getConRecords();
obj.showContacts();
}
}
47.Display related contacts using inputfield:-
page:
<apex:page standardController="account" extensions="ipf">
<apex:form id="f1">
<apex:pageBlock >
<apex:pageBlockSection >
<apex:inputField value="{!account.name}"/><br/>
<apex:commandButton value="Find" action="{!find}" reRender="out" status="mystatus"/>
</apex:pageBlockSection>
<apex:pageBlockSection id="pb">
<apex:actionStatus id="mystatus" startText="Loading......">
<apex:facet name="stop">
<apex:outputPanel id="out">
<apex:pageBlockTable value="{!conts}" var="c" id="tbl" >
<apex:column headerValue="Name" value="{!c.name}"/>
<apex:column headerValue="phone" value="{!c.phone}"/>
</apex:pageBlockTable><br/>
<apex:outputText rendered="{!(conts.size=0)}" value="No Records Found"/>
</apex:outputPanel>
</apex:facet>
</apex:actionStatus>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
class:
public with sharing class ipf
{
ApexPages.StandardController con;
account ee;
List<Account> lstaccount = new List<Account>();
List<contact> lstcontacts = new List<contact>();
public ipf(ApexPages.StandardController controller)
{
// employee__c ee=(employee__c)controller.getRecord();
con=controller;
}
public List<contact> getconts()
{
ee=(account)con.getRecord();
lstcontacts.clear();
accIds.clear();
lstaccount.clear();
if(ee.name<>null)
{
lstaccount=[select id,name from Account where name=:ee.Name];
}
for(Integer i=0;i<lstaccount.size();i++)
{
accIds.add(lstaccount[i].Id);
}
lstcontacts =[select id,name,phone,accountId from contact where accountid in : accIds];
return lstcontacts;
}
set<string> accIds = new set<string>();
public pagereference find()
{
return null;
}
}
48.Nested Lists for displaying related contacts:-
This scenario is used in the case of duplicate account names, i.e an account name exits more than one time.
In this case for everu account the contacts are displayed in a seperate table.
page:
<apex:page sidebar="false" controller="accwithcontacts2">
<apex:form >
<apex:inputText value="{!accname}"/>
<apex:commandButton value="showcontacts" action="{!showcontacts}" reRender="out" status="wait" style="color:green;" /><br/>
<apex:actionStatus id="wait" startText="Just wait....">
<apex:facet name="stop">
<apex:outputPanel id="out">
<apex:pageBlock >
<apex:repeat value="{!acc_conts}" var="r">
<apex:pageBlockTable value="{!r}" var="ac" rendered="{!(r.size!= 0)}" >
<apex:column headerValue="contacts">
{!ac.name}
</apex:column>
</apex:pageBlockTable>
<apex:outputText rendered="{!(r.size = 0)}" value=" no contacts found" style="color:red;font-size:38;" />
</apex:repeat>
</apex:pageBlock>
</apex:outputPanel>
</apex:facet>
</apex:actionStatus>
</apex:form>
</apex:page>
Class:
public with sharing class accwithcontacts2
{
string s='';
public String getInfo()
{
return s;
}
public list<account>acc;
public list<contact>cont;
public list<list<contact>>all=new list<list<contact>>();
public string accname{get;set;}
public list<list<contact>> getacc_conts()
{
all.clear();
acc=[select id,name from account where name=:accname];
for(integer i=0;i<acc.size();i++)
{
cont=[select name,accountid from contact where accountid =:acc[i].id];
all.add(cont);
}
return all;
}
public pagereference showcontacts()
{
return null;
}
}
i)SENDING eMAIL TO ALL CONTACTS OF An ACCOUNT:-
<apex:page controller="relatedcontacts">
<script>
function showModal(val){
//window.showModalDialog('/apex/secondpage?id='+val);
window.showModalDialog('/apex/contactswithcheckbox?id='+val);
}
</script>
<apex:form >
<apex:pageblock >
<apex:pageBlockSection title="Records">
<apex:pageBlockTable value="{!Accounts}" var="a">
<apex:column headerValue="Name">
<apex:commandlink value="{!a.Name}" onclick="showModal('{!a.accid}')" />
</apex:column>
<apex:column headerValue="phone" >
{!a.phone}
</apex:column>
<apex:column headerValue="website" >
{!a.website}
</apex:column>
<apex:column headerValue="taxable" >
{!a.taxable}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageblock>
</apex:form>
</apex:page>
controller:================
public with sharing class relatedcontacts {
public relatedcontacts(){
AccountData();
}
list<Account> lstacc = new list<Account>();
list<accountwrapclass> lstAccwrap = new list<accountwrapclass>();
public list<accountwrapclass> getAccounts() {
// lstacc=[select id,name,phone,website,taxable__c from Account];
return lstAccwrap ;
}
public void AccountData(){
for(Account acc:[select id,name,phone,website,taxable__c from Account]){
accountwrapclass objacc = new accountwrapclass();
objacc.Name = acc.Name;
objacc.accid = acc.id;
objacc.phone = acc.phone;
objacc.website = acc.website;
if(acc.taxable__C == true){
objacc.taxable ='yes';
}else{
objacc.taxable ='NO';
}
lstAccwrap.add(objAcc);
}
}
//wrapper class
public class accountwrapclass{
public string accid{get;set;}
public string Name{get;set;}
public string Phone{get;set;}
public string Website{get;set;}
public string taxable{get;set;}
}
}
contacts with checkbox:second page
<apex:page controller="wrapperClassController" showHeader="false" >
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Send Email" action="{!processSelected}" rerender="table" />
</apex:pageBlockButtons>
<!-- In our table we are displaying the cContact records -->
<apex:pageBlockTable value="{!contacts}" var="c" id="table">
<apex:column >
<!-- This is our selected Boolean property in our wrapper class -->
<apex:inputCheckbox value="{!c.selected}"/>
</apex:column>
<!-- This is how we access the contact values within our cContact container/wrapper -->
<apex:column value="{!c.con.Name}" />
<apex:column value="{!c.con.Email}" />
<apex:column value="{!c.con.Phone}" />
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
controller:
================
public class wrapperClassController {
public string accid ;
public wrapperClassController (){
accid = apexpages.currentpage().getparameters().get('id');
system.debug('***************Accid'+accid);
}
//Our collection of the class/wrapper objects cContact
public List<cContact> contactList {get; set;}
//This method uses a simple SOQL query to return a List of Contacts
public List<cContact> getContacts() {
if(contactList == null) {
contactList = new List<cContact>();
for(Contact c : [select Id, Name, Email, Phone from Contact where AccountId=:accid]) {
// As each contact is processed we create a new cContact object and add it to the contactList
contactList.add(new cContact(c));
}
}
return contactList;
}
public PageReference processSelected() {
//We create a new list of Contacts that we be populated only with Contacts if they are selected
List<Contact> selectedContacts = new List<Contact>();
//We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list
for(cContact cCon : getContacts()) {
if(cCon.selected == true) {
selectedContacts.add(cCon.con);
}
}
// Now we have our list of selected contacts and can perform any type of logic we want, sending emails, updating a field on the Contact, etc
System.debug('These are the selected Contacts...');
for(Contact con : selectedContacts) {
string conEmail = con.Email;
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Strings to hold the email addresses to which you are sending the email.
String[] toAddresses = new String[] {conEmail};
//String[] ccAddresses = new String[] {'smith@gmail.com'};
// Assign the addresses for the To and CC lists to the mail object.
mail.setToAddresses(toAddresses);
// mail.setCcAddresses(ccAddresses);
// Specify the address used when the recipients reply to the email.
mail.setReplyTo('support@acme.com');
// Specify the name used as the display name.
mail.setSenderDisplayName('Salesforce Support');
// Specify the subject line for your email address.
mail.setSubject('New Case Created : ' + case.Id);
// Set to True if you want to BCC yourself on the email.
mail.setBccSender(false);
// Optionally append the salesforce.com email signature to the email.
// The email address of the user executing the Apex Code will be used.
mail.setUseSignature(false);
// Specify the text content of the email.
mail.setPlainTextBody('Thank for Contacting');
mail.setHtmlBody('Thank for Contacting');
// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
// system.debug(con);
}
return null;
}
// This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
public class cContact {
public Contact con {get; set;}
public Boolean selected {get; set;}
//This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false
public cContact(Contact c) {
con = c;
selected = false;
}
}
}
==============================================================================================================================================
JAVA SCRIPT & CSS
49.Inserting records into custom object with including css:
page:
<apex:page sidebar="false" controller="DataLoadTestingClass">
<apex:form >
<div style="border:1px solid; width:200px;">
<div style="height:30px;width:150px;margin-top:20px;margin-left:20px;font-size:15px;color:blue;">
DATALOADTESTING
</div>
<table>
<tr>
<td>
Name
</td>
<td>
<apex:inputtext value="{!nameVal}"/>
</td>
</tr>
<tr>
<td>
City
</td>
<td>
<apex:inputtext value="{!cityVal}" />
</td>
</tr>
<tr>
<td>
Country
</td>
<td>
<apex:inputtext value="{!countryVal}" />
</td>
</tr>
<tr>
<td>
Phone
</td>
<td>
<apex:inputtext value="{!phoneVal}"/>
</td>
</tr>
<tr >
<td colspan="2" align="center">
<apex:commandButton value="INSERT" style="color:red;" action="{!doInsert}" />
</td>
</tr>
</table>
</div>
</apex:form>
</apex:page>
Apex Class:
public with sharing class DataLoadTestingClass {
public PageReference doInsert() {
DataloadTest__c objdlt = new DataLoadTest__c();
objdlt.name=nameVal;
objdlt.city__c=cityVal;
objdlt.country__c=countryVal;
objdlt.phone__c=phoneVal;
insert objdlt;
pagereference ref = new pagereference('/apex/insertdlttest');
ref.setredirect(true);
return ref;
}
public String phoneVal { get; set; }
public String countryVal { get; set; }
public String cityVal { get; set; }
public String nameVal { get; set; }
}
50.A sample JavaScript:
<apex:page sidebar="false">
<script>
function JSTEST()
{
var a=10,b=20;
alert('Total value is :'+(a+b));
}
</script>
<apex:form >
<apex:commandButton value="CLICKME" onclick="JSTEST();"/>
</apex:form>
</apex:page>
51.A Sample CSS for changing the Font size:-
<apex:page sidebar="false">
<style>
#fonttext{
font-size:20px;
color:green;
}
</style>
<apex:form >
<p id="fonttext"> Welcome </p>
</apex:form>
</apex:page>
52.Sum Calculation using JavaScript Function:
<apex:page sidebar="false" id="p1">
<script>
function sum(){
alert('hello');
var a=parseInt(document.getElementById('p1:f1:n1').value);
alert(a);
var b=parseInt(document.getElementById('p1:f1:n2').value);
alert(b);
alert('Total value is '+(a+b));
}
</script>
<apex:form id="f1">
N1: <apex:inputtext id="n1"/><br/>
N2: <apex:inputtext id="n2"/><br/>
<apex:commandButton value="Sum" onclick="sum()"/>
</apex:form>
</apex:page>
53.CheckBox Hide Or Unhide the components based on Checked Property:
page:
<apex:page sidebar="false" id="p1">
<script>
function HUcomponent(){
var chkResult = document.getElementById('p1:f1:chk1').checked;
alert(chkResult);
if(chkResult){
document.getElementById('p1:f1:out').style.display="block";
}
else
{
document.getElementById('p1:f1:out').style.display="none";
}
}
</script>
<apex:form id="f1">
<apex:inputcheckbox id="chk1" onclick="HUcomponent()"/> <br/>
<apex:outputpanel id="out" style="display:none;">
name: <apex:inputtext /> <br/>
City: <apex:inputtext /><br/>
<apex:commandButton value="Save"/>
</apex:outputpanel>
</apex:form>
</apex:page>
54.Removing the standard css from the pageblock table:
<apex:page standardController="DataLoadTest__c" recordSetVar="records" sidebar="false">
<style>
.headerRow th{
display:none;
}
</style>
<apex:form >
<apex:pageBlock >
<apex:pageblockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column >
{!r.Name}
</apex:column>
<apex:column >
{!r.City__c}
</apex:column>
<apex:column >
{!r.Country__c}
</apex:column>
<apex:column >
{!r.phone__c}
</apex:column>
</apex:pageBlockTable>
</apex:pageblockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
55.showModalDialog():
Gives the seperate window for any other calculations.
This belongs to javascript..
ex:
page:
<apex:page standardController="DataLoadTest__c" recordSetVar="records" sidebar="false">
<style>
.headerRow th{
display:none;
}
</style>
<script>
function showModal(val){
window.showModalDialog('/apex/second123?id='+val);
}
</script>
<apex:form >
<apex:pageBlock >
<apex:pageblockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column >
<apex:commandlink value="{!r.Name}" onclick="showModal('{!r.Id}')" />
</apex:column>
</apex:pageBlockTable>
</apex:pageblockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
56.External Javascript:
Here the external javascript file name is jsTestingExt.
page:
<apex:page sidebar="false">
<apex:includeScript value="{!$Resource.jsTestingExt}"/>
<apex:form >
<apex:commandButton value="First" onclick="one()"/>
<apex:commandButton value="Second" onclick="two()"/>
<apex:commandButton value="Three" onclick="three()"/>
</apex:form>
</apex:page>
.js file code:
function one()
{
alert('One');
}
function two()
{
alert('two');
}
function three()
{
alert('three');
}
57.Creating a menu bar:
<apex:page >
<script type="text/javascript">
function showmenu(elmnt)
{
document.getElementById(elmnt).style.visibility="visible";
}
function hidemenu(elmnt)
{
document.getElementById(elmnt).style.visibility="hidden";
}
</script>
<style>
body{font-family:arial;}
table{font-size:100%;background:white;width:50px;}
a{color:black;text-decoration:none;font:bold}
a:hover{color:#606060}
td.menu{background:lightblue}
table.menu
{
font-size:100%;
position:absolute;
visibility:hidden;
}
</style>
<apex:form >
<table >
<tr bgcolor="#FF8080">
<td onmouseover="showmenu('tutorials')" onmouseout="hidemenu('tutorials')">
Action
<table class="menu" id="tutorials" width="120">
<tr><td class="menu"><a href="https://www.gmail.com">GMail</a></td></tr>
<tr><td class="menu"><a href="https://salesforce.com">salesforce</a></td></tr>
</table></td></tr></table>
</apex:form>
</apex:page>
No comments:
Post a Comment