Search This Blog

Friday, November 27, 2015

Error: Compile Error: Constructor not defined: [SObject].()

problem:
public class SobjectConstructor {
    public SobjectConstructor () {
        Sobject sobj = new Sobject();
    }
}
When we save above piece of code, We get the error.
Solution:We cannot directly create an instance of sobject.First we need to create instance of object(salesforce standard or custom object) and then type cast to sobject
Modify the piece of code like this.
public class SobjectConstructor {
    public SobjectConstructor () {
        Account acc = new Account();
        Sobject sobj = (Sobject) acc;
    }
}

Thursday, November 26, 2015

How to query deleted records from recyclebin in salesforce

If we want to query deleted records from recycle bin,we need to use "ALL ROWS" Keyword.
Example:To query all the deleted accounts.
List<Account> accountList = [select id,name from account where isdeleted = true ALL ROWS];
system.debug('accountListaccountList'+accountList);
Output:

Opportunity stages and their associated probabilities in an organisation

In order to get opportunity stages and their associated probabilities,we need to query on standard "OpportunityStage" object.
SOQL Query: SELECT MasterLabel,DefaultProbability,Description,Id,IsActive,IsClosed,IsWon,SortOrder,CreatedDate FROM OpportunityStage.
Output:

Wednesday, November 25, 2015

Your attempt to delete the contact could not be completed because it is associated with the following portal users

We will get this type of errors sometimes when we are deleting contact.

Solution:We need to remove this user from customer portal or partner portal and then delete this.
To do this,Go to contact -->  click "Manage User" Button --> click  "Disable Customer User".

Now if you delete this contact,it will get deleted.


LEFT function in Visualforce Page

Assume "00128000003yhTi" is the AccountId in my instance.
It has one contact with name "swetha Singh".
Without Left function:
Visualforce Page:
<apex:page standardController="Account">
    <apex:pageBlock title="Account associated Contacts(Display First Word of Contact)">
        <apex:pageBlockTable value="{!account.Contacts}" var="item">
            <apex:column value="{!item.name}" headerValue="Contact Name" />
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Output: When you run the page with url like this "https://c.ap2.visual.force.com/apex/LeftFunction?id=00128000003yhTi"
With Left Function:
Visualforce Page :
<apex:page standardController="Account">
    <apex:pageBlock title="Account associated Contacts(Display First Word of Contact)">
        <apex:pageBlockTable value="{!account.Contacts}" var="item">
            <apex:variable value="{!FIND(' ',item.name)}" var="position"/>
            <apex:variable value="{!item.name}" var="test"/>
            <apex:column value="{!IF(position >0 ,LEFT(test,position-1),test)}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>
Output: When you run the page with url like this "https://c.ap2.visual.force.com/apex/LeftFunction?id=00128000003yhTi"

Tuesday, November 24, 2015

How to call apex method from a custom button in Salesforce

Apex Class:
global class ApexMethodFromButton {
    webservice static void updateLead(Id leadId) {
        Lead newLead = [select id,Name,LastName,company  from Lead where id=:leadId];
        if(newLead != null && newLead.LastName != null) {
            if(newLead.name.contains('test')) {
                newLead.company = newLead.LastName ;
                update newLead;
            }
        }
    }

}
Custom Button :
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}

var r = confirm("Are you sure want to update the company?");
if(r == true)
{
    sforce.apex.execute("ApexMethodFromButton","updateLead",{leadId:"{!Lead.Id}"});
    location.reload(true);

}



Output:


Thursday, November 19, 2015

How to prepare map of all accounts and its related contacts in apex class(map of id,list of sobject)

Suppose I want to prepare a map of all accounts and its related contact.

Map<id,List<Contact>> accountMap = new Map<id,List<Contact>> ();
List<Account> accountList =[select id,name from Account];
for(contact con:[select id,name,accountId from contact where accountId in:accountList]) {
if(accountMap.containsKey(con.accountId)) {
accountMap.get(con.accountId).add(con);
} else {
accountMap.put(con.accountId,new List<contact>{con});
}
}
system.debug('accountMapaccountMap'+accountMap);

When you run the above code snippet in workbench or developer console you will see the accountMap.
Output:

Format Date in Visualforce Page

Apex Class:
public class FormatDate {
    public date startDate {get;set;}
    public FormatDate () {
        startDate = system.TODAY();
    }
}
Visualforce Page:
<apex:page controller="FormatDate">
<apex:pageBlock>
    Date in "MMM-YYYY" Format    (Eg:Nov-2015)<br/>
    <apex:outputText value="{0,date,MMM-YYYY}">
        <apex:param value="{!startDate}" />
    </apex:outputText><br/><br/>
    Date in "DD/MM/YY" Format    (Eg:19/11/15)<br/>
    <apex:outputText value="{0,date,dd/MM/yy}">
        <apex:param value="{!startDate}" />
    </apex:outputText><br/><br/>
    Date in "DD/MMM/YYYY" Format    (Eg:19/Nov/2015)<br/>
    <apex:outputText value="{0,date,dd/MMM/yyyy}">
        <apex:param value="{!startDate}" />
    </apex:outputText><br/><br/>
    Date in "DD-MMM-YYYY" Format    (Eg:19-Nov-2015)<br/>
    <apex:outputText value="{0,date,dd-MMM-yyyy}">
        <apex:param value="{!startDate}" />
    </apex:outputText>
</apex:pageBlock>
</apex:page>
Important Note: In the <apex:outputText>  tag ,value attribute value should contain   small letter "dd" not Capital letter "DD" .For eg: value="{0,date,dd-MMM-yyyy}"
Output:

Display all months between two given dates in Visualforce Page

Apex Class:
public class DisplayAllMonthsBetweenDates {
    public list<Date> monthYearList {get;set;}
    public date startDate {get;set;}
    public date endDate {get;set;}
    public DisplayAllMonthsBetweenDates () {
        Set<Date> monthYearSet = new Set<Date>();
        monthYearList = new list<Date>();
        startDate = date.newInstance(2015, 1, 17);
        endDate = date.newInstance(2015, 11, 17);
        while(startDate <= endDate) {
            monthYearSet.add(startDate);
            startDate = startDate.AddMonths(1);
        }
        monthYearList.addAll(monthYearSet);
        monthYearList.sort();
    }
}
Visualforce Page:
<apex:page controller="DisplayAllMonthsBetweenDates">
    <apex:pageBlock title="Months between 17-1-2015 to 17-11-2015">
        <apex:pageBlockTable value="{!monthYearList }" var="newDate">
            <apex:column>
                <apex:outputText value="{0,date,MMM-YYYY}">
                <apex:param value="{!newDate}" />
                </apex:outputText>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>

</apex:page>
Output:

Assign any value to date field in Apex

Date startDate = date.newInstance(2015, 1, 17);

Saturday, November 14, 2015

Insert records in to salesforce through Java Code(using Enterprise wsdl)

Step 1:Download enterprise wsdl from salesforce.com and save it as xml file
for eg:enterprisewsdl.xml
Go to setup --> API --> "Generate Enterwise WSDL".
                                     
On clicking "Generate" Button you will find wsdl file like this.

Step 2: Download any wsc file from below link
         https://code.google.com/p/sfdc-wsc/downloads/list

I downloaded wsc-19.jar.
Step 3:Place wsdl file and wsc file all in one folder.


Step 4:Open command prompt and move to that specified folder path and run the following command.
Assume "c:\Action Items\JavaIntegration" is the path of folder .
c:\Action Items\JavaIntegration>java -classpath wsc-19.jar com.sforce.ws.tools.wsdlc enterprisewsdl.xml enterprise.jar
In the above command, enterprisewsdl is the path of wsdl which we have downloaded earlier.
It will generate one enterprise.jar file as shown in the image below.
Step 5:write one java class as shown below.Add the jar files "wsc-19.jar" and generated "enterprise.jar" to that class.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.GetUserInfoResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
public class AccountInsertion {
public String authEndPoint = "";
    EnterpriseConnection con;
    private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String[] args) {
AccountInsertion sample = new AccountInsertion("https://login.salesforce.com/services/Soap/c/29");
        if ( sample.login()) {
sample.insertAcct();
        }
    }
    public AccountInsertion(String authEndPoint) {
this.authEndPoint = authEndPoint;
    }
    public String getUserInput(String prompt) {
String result = "";
        try {
System.out.print(prompt);
            result = reader.readLine();
        }
        catch (IOException ioe) {
ioe.printStackTrace();
        }
        return result;
    }
    public boolean login() {
boolean success = false;
        String userId = getUserInput("UserID: ");
        String passwd = getUserInput("Password + Security Token: ");
        try {
/* Setting up Username and Password */
            ConnectorConfig config = new ConnectorConfig();
            config.setAuthEndpoint(authEndPoint);
            config.setUsername(userId);
            config.setPassword(passwd);
            config.setCompression(true);
            System.out.println("AuthEndPoint: " + authEndPoint);
            config.setTraceFile("insertLogs.txt");
            config.setTraceMessage(true);
            config.setPrettyPrintXml(true);
            System.out.println("\nLogging in ...\n");
            con = new EnterpriseConnection(config);
            GetUserInfoResult userInfo = con.getUserInfo();
            System.out.println("UserID: " + userInfo.getUserId());
            System.out.println("\nLogged in Successfully\n");
            success = true;
        }
        catch (ConnectionException ce) {
ce.printStackTrace();
        }
        catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
        }
        return success;
    }
    public void insertAcct() {
/* Getting Account details */
String acctName = getUserInput("Enter Account name:");
String phoneNo = getUserInput("Enter phone no:");
Account acct = new Account();
/* Setting Account details */
acct.setName(acctName);
acct.setPhone(phoneNo);
Account[] accts = { acct };
        try {
System.out.println("\nInserting...\n");
/* Inserting account records */
con.create(accts);
   }
   catch (ConnectionException ce) {
ce.printStackTrace();
   }
   System.out.println("\nAccount has been inserted successfully.");
    }
}
Step 6:Run the java class.
Input:
UserID: username
Password + Security Token: passwordsecuritytoken
AuthEndPoint: https://login.salesforce.com/services/Soap/c/29

Logging in ...

UserID: 00528000000St5nAAC

Logged in Successfully

Enter Account name:Test Java Account
Enter phone no:9999999899

Inserting...
Account has been inserted successfully.

Output :

Friday, November 13, 2015

Alignment or Indentation of code in salesforce

Step 1: If you want to align Apex code, visualforce Page code or Apex trigger code automatically ,

open that particular page or class or trigger in developer console.

Step 2: Select all code(press ctrl+A) and then go to Edit --> Fix Indentation. On clicking "Fix Indentation" the code will get aligned automatically.




Code before Alignment:
<apex:page controller="AccountAndContactsDisplay" action="{!displayAccounts}">
<apex:pageBlock title="Account and its Contacts">
<apex:pageBlockTable value="{!accountList}" var="acc">
<apex:column value="{!acc.name}" headerValue="Account Name"/>
<apex:column breakBefore="true">
<apex:pageBlock title="{!acc.name} related Contact Details">
<apex:pageBlockTable value="{!acc.contacts}" var="con" >
<apex:column value="{!con.name}" headerValue="Contact Name"/>
</apex:pageBlockTable>
</apex:pageBlock>  
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>


Code after Alignment :


<apex:page controller="AccountAndContactsDisplay" action="{!displayAccounts}">
    <apex:pageBlock title="Account and its Contacts">
        <apex:pageBlockTable value="{!accountList}" var="acc">
            <apex:column value="{!acc.name}" headerValue="Account Name"/>
            <apex:column breakBefore="true">
                <apex:pageBlock title="{!acc.name} related Contact Details">
                    <apex:pageBlockTable value="{!acc.contacts}" var="con" >
                        <apex:column value="{!con.name}" headerValue="Contact Name"/>
                    </apex:pageBlockTable>
                </apex:pageBlock>  
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Get Salesforce Instance Url

Apex Class :
public class SalesforceInstanceUrlGenerator {
    public string instanceUrl {get;set;}
    public SalesforceInstanceUrlGenerator () {
        instanceUrl = System.URL.getSalesforceBaseUrl().toExternalForm();
    }
}
Visualforce Page :
<apex:page controller="SalesforceInstanceUrlGenerator">
       <B>Salesforce Instance Url</B> :{!instanceUrl}
</apex:page>

Output :

Nested Page block table (Display all accounts along with its contacts in visualforce page)

BreakBefore attribute in <apex:column> : A Boolean value that specifies whether the
 column should begin a new row in the table. If set to true, the column begins a new row.
Apex Class:
public class AccountAndContactsDisplay {
    public list<Account> accountList {get;set;}
    public AccountAndContactsDisplay () {
    }
    public void displayAccounts() {
        accountList = [select id,name,(select id,name from contacts) from Account limit 5];
    }
}
Visualforce Page:
<apex:page controller="AccountAndContactsDisplay" action="{!displayAccounts}">
    <apex:pageBlock title="Account and its Contacts">
        <apex:pageBlockTable value="{!accountList}" var="acc">
            <apex:column value="{!acc.name}" headerValue="Account Name"/>
            <apex:column breakBefore="true">
                <apex:pageBlock title="{!acc.name} related Contact Details">
                    <apex:pageBlockTable value="{!acc.contacts}" var="con" >
                        <apex:column value="{!con.name}" headerValue="Contact Name"/>
                    </apex:pageBlockTable>
                </apex:pageBlock>  
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>
Output :

How to reset security token in salesforce

Step 1: Go to user(at the top right) --> My settings --> Personal --> Reset My Security Token.

Step 2:When you click on "Reset Security Token" button, an email will be sent to the email specified along with the new security token details.

The email will be like this.




Saturday, November 7, 2015

BreadCrum functionality in Visualforce Page

Apex Class:
public class BreadCrum {
    public boolean renderSection1 {get;set;}
    public boolean renderSection2 {get;set;}
    public boolean renderSection3 {get;set;}
    public BreadCrum () {
        renderSection1 = true;
        renderSection2 = false;
        renderSection3 = false;
    }
    public void displaySection1() {
        renderSection1 = true;
        renderSection2 = false;
        renderSection3 = false;
    }
    public void displaySection2() {
        renderSection1 = false;
        renderSection2 = true;
        renderSection3 = false;
    }
    public void displaySection3() {
        renderSection1 = false;
        renderSection2 = false;
        renderSection3 = true;
    }
}
Visualforce Page:
<apex:page Id="genericPageId" sidebar="false" controller="BreadCrum">
  <apex:form id="form1">
        <script language='JavaScript1.2' src='/js/functions.js'></script>
        <script src='/soap/ajax/9.0/connection.js' type='text/javascript'></script>
        <script id='clientEventHandlersJS' language='javascript'/>
         <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
         <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
       <script>

        function colorPageBlock(pageblock, color) {
            if (pageblock != null) pageblock.firstChild.style.cssText = "background-color: " + color + ";";
        }
        function displaySection1() {
            renderSection1();
        }
        function displaySection2() {
            renderSection2();
        }
        function displaySection3() {
            renderSection3();
        }
        function toggleClass(el){
            var kids = document.getElementById('menu1').children;
            for(var i = 0; i < kids.length; i++){
                kids[i].className = "inActive";
            }
            el.className = "active";
        }
       
    </script>
       
         <style>
             .clsCenter{
             text-align:center;
             }
           
             .inActive {            
             background: white;
             color: black;
             transition: all 0.5s;
             }            
        /*custom font*/
        @import url(http://fonts.googleapis.com/css?family=Merriweather+Sans);      
        * {margin: 0; padding: 0;}      
        html, body {min-height: 100%;}      
     
       
        .breadcrumb {
        /*centering*/
        display: inline-block;
        box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.35);
        overflow: hidden;
        border-radius: 5px;
        /*Lets add the numbers for each link using CSS counters. flag is the name of the counter. to be defined using counter-reset in the parent element of the links*/
        counter-reset: flag;
        }
       
        .breadcrumb a {
        text-decoration: none;
        outline: none;
        display: block;
        float: left;
        font-size: 12px;
        line-height: 36px;
        color: white;
        /*need more margin on the left of links to accomodate the numbers*/
        padding: 0 10px 0 60px;
        background: #666;
        background: linear-gradient(#666, #333);
        position: relative;
        }
        /*since the first link does not have a triangle before it we can reduce the left padding to make it look consistent with other links*/
        .breadcrumb a:first-child {
        padding-left: 46px;
        border-radius: 5px 0 0 5px; /*to match with the parent's radius*/
        }
        .breadcrumb a:first-child:before {
        left: 14px;
        }
        .breadcrumb a:last-child {
        border-radius: 0 5px 5px 0; /*this was to prevent glitches on hover*/
        padding-right: 20px;
        }
       
        /*hover/active styles*/
        .breadcrumb a.active, .breadcrumb a:hover{
        background: #333;
        background: linear-gradient(#333, #000);
        }
        .breadcrumb a.active:after, .breadcrumb a:hover:after {
        background: #333;
        background: linear-gradient(135deg, #333, #000);
        }
       
        /*adding the arrows for the breadcrumbs using rotated pseudo elements*/
        .breadcrumb a:after {
        content: '';
        position: absolute;
        top: 0;
        right: -18px; /*half of square's length*/
        /*same dimension as the line-height of .breadcrumb a */
        width: 36px;
        height: 36px;
        /*as you see the rotated square takes a larger height. which makes it tough to position it properly. So we are going to scale it down so that the diagonals become equal to the line-height of the link. We scale it to 70.7% because if square's:
        length = 1; diagonal = (1^2 + 1^2)^0.5 = 1.414 (pythagoras theorem)
        if diagonal required = 1; length = 1/1.414 = 0.707*/
        transform: scale(0.707) rotate(45deg);
        /*we need to prevent the arrows from getting buried under the next link*/
        z-index: 1;
        /*background same as links but the gradient will be rotated to compensate with the transform applied*/
        background: #666;
        background: linear-gradient(135deg, #666, #333);
        /*stylish arrow design using box shadow*/
        box-shadow:
        2px -2px 0 2px rgba(0, 0, 0, 0.4),
        3px -3px 0 2px rgba(255, 255, 255, 0.1);
        /*
        5px - for rounded arrows and
        50px - to prevent hover glitches on the border created using shadows*/
        border-radius: 0 5px 0 50px;
        }
        /*we dont need an arrow after the last link*/
        .breadcrumb a:last-child:after {
        content: none;
        }
        /*we will use the :before element to show numbers*/
        .breadcrumb a:before {
        content: counter(flag);
        counter-increment: flag;
        /*some styles now*/
        border-radius: 100%;
        width: 20px;
        height: 20px;
        line-height: 20px;
        margin: 8px 0;
        position: absolute;
        top: 0;
        left: 30px;
        background: #444;
        background: linear-gradient(#444, #222);
        font-weight: bold;
        }
       
       
        .flat a, .flat a:after {
        background: white;
        color: black;
        transition: all 0.5s;
        }
        .flat a:before {
        background: white;
        box-shadow: 0 0 0 1px #ccc;
        }
        .flat a:hover{
        background: #C8EBF7;
        }
        .flat a.active,
        .flat a:hover:after, .flat a.active:after{
        background: #8AC8DC;
        }
    </style>
        <apex:actionStatus id="statusSaveTrip" stopText="" >
            <apex:facet name="start">
                <div>
                    <div class="popupBackground" />
                    <div class="PopupPanel">
                        <table  width="100%" height="100%">
                            <tr>
                                <td align="center"><b>Please Wait</b></td>
                            </tr>
                            <tr>
                                <td align="center"><img src="/img/loading24.gif"/></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </apex:facet>
        </apex:actionStatus>
        <center>
            <div>
                &nbsp;    &nbsp;&nbsp;&nbsp;
            </div>
            <apex:outputPanel >
                <div class="breadcrumb flat" id="menu1" align="center">
                    <a href="#" class="active" onclick="displaySection1(),toggleClass(this)" >Section 1</a>
                    <a href="#" class="inActive" onclick="displaySection2(),toggleClass(this)" >Section 2</a>
                    <a href="#" class="inActive" onclick="displaySection3(),toggleClass(this)" >Section 3</a>
                    <a href="#" class="inActive" onclick = "javascript:CloseAndRefresh(),toggleClass(this)">Finish</a>
                </div>
            </apex:outputPanel>
        </center><br/>
       
       <apex:pageBlock title="Bread Crum Example" id="mainBlock">
            <apex:pageBlockSection title="Section 1" columns="2" id="section1" collapsible="false" rendered="{!renderSection1}">
            <script>colorPageBlock(document.getElementById("{!$Component.section1}"), "#29A3CC");</script>
            This is Section 1
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Section 2" columns="2" id="section2" collapsible="false" rendered="{!renderSection2}">
            <script>colorPageBlock(document.getElementById("{!$Component.section2}"), "#29A3CC");</script>
            This is Section 2
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Section 3" columns="2" id="section3" collapsible="false" rendered="{!renderSection3}">
            <script>colorPageBlock(document.getElementById("{!$Component.section3}"), "#29A3CC");</script>
            This is Section 3
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:actionFunction name="renderSection1" action="{!displaySection1}" reRender="mainBlock,section1"/>
        <apex:actionFunction name="renderSection2" action="{!displaySection2}" reRender="mainBlock,section2"/>
        <apex:actionFunction name="renderSection3" action="{!displaySection3}" reRender="mainBlock,section3"/>
    </apex:form>
</apex:page>
Output:

Tuesday, November 3, 2015

Disable entire visualforce page while saving data(or) Display "loading image" in visualforce page

Visualforce Page:
<apex:page standardController="Account">
<style>
    #loading-curtain-div {
    height:0px;
    width:100%;
    position:absolute;
    z-index:5;
    //-webkit-transition: all 0.30s ease-out;
    //-moz-transition: all 0.30s ease-out;
    }
   
    /* This is for the full screen DIV */
    .popupBackground {
    /* Background color */
    background-color:black;
    opacity: 0.20;
    filter: alpha(opacity = 20);
   
    /* Dimensions */
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 998;
    position: absolute;
   
    /* Mouse */
    cursor:wait;
    }
   
    /* This is for the message DIV */
    .PopupPanel {
    /* Background color */
    border: solid 1px #e3deb8;
    background-color: #ECECEC;
   
    /* Dimensions */
    left: 50%;
    width: 300px;
    margin-left: -100px;
    top: 50%;
    height: 50px;
    margin-top: -25px;
    z-index: 999;
    position: fixed;
   
    /* Mouse */
    cursor:pointer;
    }
</style>

<apex:actionStatus id="statusSave" stopText="">
    <apex:facet name="start">
        <div>
            <div class="popupBackground" />
            <div class="PopupPanel">
                <table  width="100%" height="100%">
                    <tr>
                        <td align="center"><b>Please Wait</b></td>
                    </tr>
                    <tr>
                        <td align="center"><img src="/img/loading24.gif"/></td>
                    </tr>
                </table>
            </div>
        </div>
    </apex:facet>
</apex:actionStatus>
<apex:form>
    <apex:pageBlock title="Account" mode="edit" id="pb">
        <apex:pageBlockButtons>
            <apex:commandButton action="{!save}" value="Save" status="statusSave" rerender="pb">
                <apex:actionStatus id="actStatusId">
                    <apex:facet name="start">
                        <img src="/img/loading.gif" />
                    </apex:facet>
                </apex:actionStatus>
        </apex:commandButton>
        </apex:pageBlockButtons>
        <apex:pageBlockSection title="Account Section" columns="2">
            <apex:inputField value="{!account.name}"/>
            <apex:inputField value="{!account.site}"/>
            <apex:inputField value="{!account.type}"/>
            <apex:inputField value="{!account.accountNumber}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>
Output:
Before clicking save

After Clicking Save















How to access custom Label in Apex

Suppose If I have created  " suplierAccountId"  as a custom Label as shown in the image below


Then we can use this custom Label as shown below.
string labelValue =Label.suuplierAccountId;
system.debug('labelValuelabelValue'+labelValue );
Output: labelValuelabelValue 00128000003yhTi

How to query records based on record type name in apex

Suppose "Supplier" is the record type name in Account object
Then the query to retrieve accounts of this recordtype is
list<Account> accountList =[select id,name,recordtypeId from Account where recordType.name=:'Supplier'];
system.debug('accountListaccountList'+accountList );


Get Record Type Id by Name in apex

Suppose I have created "Supplier" as record type in account object as shown in the image below.

Now to get id of this record type,use the code below
Id recordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Supplier').getRecordTypeId();
system.debug('recordTypeIdrecordTypeId'+recordTypeId );

Output: recordTypeIdrecordType Id012280000009tHsAAI
Here 18 digit Id is displayed.

Sunday, November 1, 2015

How to assign values to multiselect picklist field in apex

In the example below Alphabets__c is a multiselect picklist field in Account object.
In order to set values to multi-select picklist ,first we need to form a string with
each selected value followed by ";" and then assign this string to multiselect picklist field.
Apex Class :
public class MutlipicklistFieldValue {
    public MutlipicklistFieldValue () {
    }
    public void insertAccount() {
        Account newAccount = new Account();
        newAccount.name = 'Testing Multipicklist Value';
        string values = 'A;B;D';
        newAccount.Alphabets__c = values;
        insert newAccount;
        system.debug('newAccountnewAccount'+newAccount);
    }
}
Visualforce Page :
<apex:page controller="MutlipicklistFieldValue" action="{!insertAccount}">
</apex:page>

Output: