Regular Expression for email validation using Apex in Salesforce

Sample Regular Expression for email validation using Apex is given below

Sample Code:
                

                if(Pattern.matches('[a-zA-Z0-9._-]+@[a-zA-Z]+.[a-zA-Z]{2,4}', email))
                {
                    //success
                }
                else
                {
                    //error       
                }

Cheers!!!

recordSetVar in Visualforce page

The recordSetVar attribute not only indicates that the page uses a list controller, it can indicates the variable name of the record collection. This variable can be used to access data in the record collection.

Sample code:

<apex:page standardController="Account" recordSetVar="accounts" tabstyle="account" sidebar="false">
    <apex:pageBlock >
        <apex:pageBlockTable value="{!accounts}" var="a">
            <apex:column value="{!a.name}"/>
         </apex:pageBlockTable>
     </apex:pageBlock>
</apex:page>


How to Save or Update record using Force.com Explorer?

To Save or Update record using Force.com Explorer, follow the below steps

1. Open Force.com Explorer.

2.Login into Force.com Explorer using your username, password and security token.

Username: username of your organization
Password: password + security token


3. Query some records.


4. Double click the value to edit it. It will be highlighted.


5. Enter your value and press 'Enter', you will get 'Save' or 'Cancel' options.


6. Click 'Save' and click 'Ok' in the next confirm window to update in your organization.


7. You will get an alert message whether record has been saved successfully. Click 'Ok' to resume.

Generating JSON in Visualforce page in Salesforce

JSON stands for “Java Script Object Notation“.

JSON.serialize() is used to generate JSON. It is a lightweight data-interchange format.

JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Sample Code:

Visualforce page:

<apex:page controller="sample" action="{!parseJson}">
    {!text1}
</apex:page>


Apex Controller:

public class sample
{   
    public String text1 {get;set;}
     
    public sample()
    {
        
    }   
    public void parseJson()
    {
        String soql = 'SELECT Name FROM Account LIMIT 5';
        List<Account> acct = Database.Query(soql);
        text1 = JSON.serialize(acct);
    }   
}


Output:


JSON.deserialize() method is used to deserialize the specified JSON string into an Apex object of the specified type.

How to convert lead using Apex?

Sample code:

Lead myLead = new Lead(LastName = 'Foo', Company='Foo Bar');
insert myLead;    
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(myLead.id);
lc.ConvertedStatus = 'Closed - Converted';
Database.LeadConvertResult lcr = Database.convertLead(lc);                
System.assert(lcr.isSuccess());

Cheers!!!

apex:actionPoller

     A timer that sends an AJAX update request to the server according to a time interval that you specify. The update request can then result in a full or partial page update. You should avoid using this component with enhanced lists.

Visualforce page:

 <apex:page controller="exampleCon">
    <apex:form>
        <apex:outputText value="Watch this counter: {!count}" id="counter"/>
        <apex:actionPoller action="{!incrementCounter}" rerender="counter" interval="15"/>
    </apex:form>
</apex:page>
                    
Apex Code: 
          
public class exampleCon {
    Integer count = 0;
          
    public PageReference incrementCounter() 
{
        count++;
        return null;
    }
          
    public Integer getCount() 
{
        return count;
    }
}


Attribute:

interval  -  The time interval between AJAX update requests, in seconds. This value must be 5 seconds or greater, and if not specified, defaults to 60 seconds. Note that the interval is only the amount of time between update requests. Once an update request is sent to the server, it enters a queue and can take additional time to process and display on the client. 

Cheers!!!

Account hierarchy in Salesforce

 The account hierarchy shows you the accounts that are associated through the Parent Account field, giving you a global view of a company and its subsidiaries. In the hierarchy, accounts are indented to show that they are subsidiaries of the parent account above them.

    To view the account hierarchy, click View Hierarchy next to the account name on the account detail page. The Account Hierarchy page displays up to 500 child accounts. If you don’t have access to certain accounts that appear on the Account Hierarchy page, the columns for those accounts won’t display details.
    To list an account as a subsidiary, edit the subsidiary account and type the name of an existing account in the Parent Account field. Alternatively, you can click the lookup icon to search for (or optionally, create) a parent account.

The parent account must be an existing account before it can be entered and saved in this field.

For companies with multiple office locations, you can also use the Account Site field to distinguish among the locations.

If your organization uses divisions, accounts that are associated via the Parent Account field do not need to be in the same division.

The Parent Account field and the View Hierarchy link are not supported for person accounts.



Cheers!!!

Email validation using Apex in Salesforce

Visualforce page:

<apex:page controller="testController">
    <apex:form id="myform">
    <apex:pagemessages />
    <apex:pageBlock id="myblock">
        Email Address: <apex:inputText value="{!email}" id="email"/><br/><br/>
        <apex:commandButton value="Click me!" action="{!checkEmail}"/>
    </apex:pageBlock>
    </apex:form>
</apex:page>


Apex Code:

public class testController
{
    public String email { get; set; }
    public void checkEmail()
    {

        if(!Pattern.matches('[a-zA-Z0-9._-]+@[a-zA-Z]+.[a-zA-Z]{2,4}[.]{0,1}[a-zA-Z]{0,2}', email))
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Check your email'));

        }
    }
}


Cheers!!!

How to add picklist values to existing picklist in Salesforce?

To add picklist values to existing picklist in Salesforce, follow the below steps

1. Select the picklist field.



2. Click ‘New’ Button in Picklist values and add it.



Cheers!!!

Calling Apex method from a Custom Button

To call Apex method from Custom Button, follow the below steps

1. Create a custom button and enter the following code

Syntax:

{!REQUIRESCRIPT("/soap/ajax/12.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/12.0/apex.js")}

sforce.apex.execute("Class_Name","Method_Name",{parameter_Name:"value"});
location.reload(true);

Code:

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

var r = confirm("Record will not be able to edit after sending it to Approval Process.\nAre you sure want to send it for approval process?");
if(r == true)
{
    sforce.apex.execute("memberApproval","callApproval",{localId:"{!Member__c.Id}"});
    alert("Sent it for Approval");
}



2. Create a apex class with following code

Syntax:

global class ClassName {
    webservice static void methodName(DataType variable) 
                …………………        
                …………………
                …………………
    }
}

Code:

global class memberApproval {
    webservice static void callApproval(Id localId) 
                Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
                req1.setComments('Submitted for Approval');
                req1.setObjectId(localId);
                Approval.ProcessResult res = Approval.Process(req1);                  
    }
}

Output:



Cheers!!!

Map data type in Salesforce

A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

Example:

Map<Integer, Account> m =  new Map<Integer, Account>();

Map<Integer, Account> m = new Map<Integer, Account>{1=> new Account(name='test')};

Map<Integer, String>  m = new Map<Integer, String>{1=>'a',2=>'b'};
m.put(3,'c'); // Assigning values using put()
String str = m.get(2) // returns b
List<Integer> keys = new List<Integer>();
keys = m.keySet(); //Returns the keys from Map
List<String> val = new List<String>();
val = m.values();  //Returns the values from Map
m.containsKey(3); //Returns true if the map contains a mapping for the specified key.
//If the key is a string, the key value is case-sensitive

Securing Apex Class

To set Apex class security from the class list page:
  1. Click Your Name | Setup | Develop | Apex Classes.
  2. Next to the name of the class that you want to restrict, click Security.
  3. Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click Remove.
  4. Click Save.
To set Apex class security from the class detail page:
  1. Click Your Name | Setup | Develop | Apex Classes.
  2. Click the name of the class that you want to restrict.
  3. Click Security.
  4. Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click Remove.
  5. Click Save.


How to grant permission for Administrator to login as you?

To assist with support issues, you may grant your administrator or support personnel the ability to login as you and access your data.

Go to My Settings --> Personal --> Grant Account Login Access.




Force.com IDE

The Force.com IDE is a powerful client application for creating, modifying, testing and deploying Force.com applications. Based on the Eclipse platform, it provides a comfortable environment for programmers familiar with integrated development environments, allowing you to code, compile, test, and deploy all from within the IDE itself.
  • The Force.com IDE is the only tool you need to write and manage Apex classes and triggers. It locates syntax errors and displays inline auto-complete tips for Apex built-in objects. 
  • The Apex Test Runner executes unit tests and integrates error messages, debug output, and code coverage reports.  
  • Create and edit Visualforce pages, components, static resources, and controllers.
    Develop and test your project against a Sandbox or Developer Edition organization, then deploy the finished application into your production organization with the Deploy to Server wizard.
  • View your Salesforce organization's schema and construct and execute SOQL queries from within the Force.com IDE. Similar to the Apex Explorer, the Schema Explorer shows information about all standard and custom objects and fields.
Click here to install Force.com IDE in Eclipse.


How to find out what Salesforce edition you have?

To find out what Salesforce edition you have, use the below code

SELECT OrganizationType FROM Organization

Output from Force.com Explorer:

Where to check the Scheduled jobs in Salesforce?

To check the Scheduled jobs in Salesforce, go to Setupu --> Administration Setup --> Monitoring --> Scheduled Jobs.

Is there a limit to the number of records one can access using Explorer?

There is no limit to the number of records one can access using Explorer.



I have retrieved 6,61,603 records.

How to reference Email template using Apex

Sample Code:

trigger happyBirthday on Member__c (after insert)
{
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    List<String> ccAddresses = new List<String>();
    ccAddresses.add('magualn.d@igate.com');
    for(Member__c mem:trigger.new)
    {      
        mail.setTemplateId('00XU0000000YOlG'); //Id of the Email Template
        mail.setCcAddresses(ccAddresses);
        mail.setTargetObjectId('005U0000000gpc1'); // Id of Contact or Lead or User
        mail.setSaveAsActivity(false);
        mail.setWhatId(mem.Id); //Optional field to ensure proper merging of objects in template
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

Collection size exceeds maximum size of 1000 error

It means List, Set & Map size exceeded more than 1000 to be shown on the Visualforce page.

To avoid this, use wrapper class and get set of first 1000 records, save it and then retrieve the next and so on.

Sample code:

Visualforce page:


<apex:page controller="thousandLimit">   
   <apex:pageBlock >
      <apex:repeat value="{!thousandBlocks}" var="block">
            <apex:pageBlockTable value="{!block.cases}" var="c">
            <apex:column value="{!c.CaseNumber}"/>
            <apex:column value="{!c.owner.name}"/>
            <apex:column value="{!c.App_Process__c}"/>
            <apex:column value="{!c.Load__c}"/>
            <apex:column value="{!c.subject}"/>
            <apex:column value="{!c.Estimated_Completion_Date__c}"/>  
            <apex:column value="{!c.Complete__c}"/>
            <apex:column value="{!c.Priority}"/>
            <apex:column value="{!c.Case_Age_Days__c}"/>                   
            </apex:pageBlockTable>
        </apex:repeat>
     </apex:pageBlock> 
</apex:page>

 Apex Controller:

public class thousandLimit
{
    private limitWrapper[] thousandBlocks = new limitWrapper[]{};
   
    private final integer listLimit;
   
    public thousandLimit()
    {
        listLimit = 1000;
    }
   
    public limitWrapper[] getthousandBlocks()
    {
        thousandBlocks = new limitWrapper[]{};
       
        integer counter = 0;
        integer loopCount = 0;
        case[] tmpcase = new case[]{};
       
        for(case c:[select CaseNumber,owner.name,App_Process__c,Load__c,subject,Estimated_Completion_Date__c,Complete__c,Priority,Case_Age_Days__c from Case
                where (Status != 'Closed' or Status != 'Declined') and Estimated_Completion_Date__c = null and owner.Alias like 'EA%' order by owner.name])
        {
            if(counter < listLimit)
            {
                tmpcase.add(c);
                counter++;
            }
            else
            {
                loopCount++;
                thousandBlocks.add(new limitWrapper(tmpcase,loopCount));
                tmpcase = new case[]{};
                tmpcase.add(c);
                counter = 0;
            }           
        }
       
        if(thousandBlocks.size() == 0)
        {
            loopCount++;
            thousandBlocks.add(new limitWrapper(tmpcase,loopCount));
        }
       
        return thousandBlocks;
    }
   
    public class limitWrapper
    {
        public case [] cases {get;set;}
        public integer blockNumber {get;set;}
        public limitWrapper(case[] accs, integer i)
        {
            cases = accs;
            blockNumber = i;
        }
       
    }
}


Cheers!!!

Cannot Reference Converted lead error

  1. This error means that the Lead record has been converted. 
  2. Once converted, the Lead record cannot be updated. 
  3. The Lead object has an IsConverted property. Using that you can check to whether lead has been converted.

How to get picklist values of Standard object picklist?

Sample code:

Visualforce page:

<apex:page Controller="sample">

<script type="text/javascript">

</script>
   
    <apex:form >
   
    <apex:pageMessages />
   
    <apex:pageBlock >
        <apex:pageBlockSection columns="2">
            <apex:pageblockSectionItem >
                <apex:outputLabel value="Ownership"/>
            </apex:pageblockSectionItem>       
            <apex:pageblockSectionItem >
                <apex:selectList value="{!ownership}" size="1" >
                    <apex:selectOptions value="{!ownershipOptions}"/>
                </apex:selectList>               
            </apex:pageblockSectionItem>           
        </apex:pageBlockSection>       
    </apex:pageBlock>

    </apex:form>

</apex:page>


Apex Controller:

public class sample
{   
    public String ownership {get;set;}
     
    public sample()
    {
       
    }

    public List<SelectOption> getownershipOptions()   
    {   
        List<SelectOption> options =  new List<SelectOption>();   
        options.add(new selectOption('None','--- None ---'));   
        Schema.DescribeFieldResult fieldResult = Account.ownership.getDescribe();   
        List<Schema.picklistEntry> ple = fieldResult.getPicklistValues();   
        for(Schema.picklistEntry f:ple)   
        {   
            options.add(new selectOption(f.getLabel(),f.getValue()));                   
        }   
        return Options;   
    }     
}



How to display Standard controller Picklist using Apex

The below code is used to display Rating picklist of standard object Account.

<apex:page standardController="Account">

    <apex:form >
   
    <apex:pageMessages />
   
    <apex:pageBlock >
        <apex:pageBlockSection columns="2">
            <apex:pageblockSectionItem >
                <apex:outputLabel value="Rating"/>
            </apex:pageblockSectionItem>       
            <apex:pageblockSectionItem >
                <apex:inputField value="{!Account.Rating}"/>             
            </apex:pageblockSectionItem>           
        </apex:pageBlockSection>       
    </apex:pageBlock>

    </apex:form>

</apex:page>


Output:


How to avoid comma atlast while displaying error



Sample Code:

List<String> mail = new List<String>();
String error = '';

Integer i;
Integer len;
mail.add(test@test.com);
mail.add(test1@test.com);
mail.add(test2@test.com);
mail.add(test3@test.com);

len = mail.size();
i = 0;
for(String temp:mail)
{
    if(i>len-1)
    {
        error = error + temp + ',';
    }
    else
    {
        error = error + temp;
    }
    i++;

}
<iframe> not working in Home page component, enable 'Show HTML' checkbox before typing the HTML code.

Example:

<iframe src="/apex/Sample"></iframe>

How to disable another checkbox field checkbox if i check one checkbox in checkbox field

Sample Code:

Visualforce page:


<apex:page controller="sample">

<script type="text/javascript">

</script>
  
    <apex:form >
  
    <apex:pageMessages />
  
    <apex:pageBlock >
        <apex:pageBlockSection columns="2">
            <apex:pageblockSectionItem >
                <apex:outputLabel value="Metro"/>
            </apex:pageblockSectionItem>      
            <apex:pageblockSectionItem >              
                <apex:inputCheckbox value="{!metro}">           
                    <apex:actionSupport event="onchange" reRender="a" action="{!demo}"/>
                </apex:inputCheckbox>
            </apex:pageblockSectionItem>
            <apex:pageblockSectionItem >
                <apex:outputLabel value="City"/>
            </apex:pageblockSectionItem>
            <apex:pageblockSectionItem >
                <apex:inputCheckbox value="{!city}" id="a" disabled="{!bool}"/>
            </apex:pageblockSectionItem>          
        </apex:pageBlockSection>      
    </apex:pageBlock>

    </apex:form>

</apex:page>


Apex Code:

public class sample
{  
    public Boolean metro {get;set;}
    public Boolean city {get;set;}
    public Boolean bool {get;set;}
  
    public sample()
    {
      
    }
  
    public void demo()
    {
        if(metro)
        {
            bool = true;
        }
        else
        {
            bool = false;
        }       
    }
    
}


Cheers!!!

On-Demand Email to Case in Salesforce

With salesforce.com, you can efficiently resolve and correspond with customer inquiries via email. Track and view all email threads regarding a customer service issue, and let your customers send inquiries to email addresses that automatically convert customer emails to cases.

1. Go to Setup --> Build --> Customize --> Cases --> Email-to-Cases.



2.  Click 'Edit' button.


3. Enable' Email-to-Case' and 'On-Demand Service'.


4. Click 'Save' button.

5. Click 'New' button in Routing addresses. Select 'Outlook' for outlook users and 'Email2Case' for other mail service users.


6. Enter Routing name and Email address. If you want to create task from Email, check Create Task from Email checkbox and select the task status. Select Case origin and Case status.


7. Click 'Save' Button.

8. Click 'Ok' button to receive Verification email.


9. Verify the routing address by clicking the link in the verification email.


10. Send email to 'Email Services Address'.




11. Check it in your Salesforce organization whether case is created in Case object.


12. Click to view it in detail page.


Dynamically making a field required using Apex in Salesforce

Sample Code:

Visualforce Code:

<apex:page controller="sample">
   
    <apex:form >
   
    <apex:pageMessages/>
   
    <apex:pageBlock>
        <apex:pageBlockSection columns="2">
            <apex:pageblockSectionItem>
                <apex:outputLabel value="Known City"/>
            </apex:pageblockSectionItem>       
            <apex:pageblockSectionItem>               
                <apex:inputCheckbox value="{!knwCity}">            
                    <apex:actionSupport event="onchange" reRender="a"/>
                </apex:inputCheckbox>
            </apex:pageblockSectionItem>
            <apex:pageblockSectionItem>
                <apex:outputLabel value="City"/>
            </apex:pageblockSectionItem>           
            <apex:pageblockSectionItem>
                <apex:inputText value="{!city}" required="{!bool}" id="a"/>
            </apex:pageblockSectionItem>     
            <apex:commandButton value="Save" action="{!save}"/>     
        </apex:pageBlockSection>       
    </apex:pageBlock>

    </apex:form>

</apex:page>


Apex Class:

public class sample
{
    public String city {get;set;}
    public Boolean knwCity {get;set;}
    public Boolean bool {get;set;}
       
    public void save()
    {
        bool = false;
        if(knwCity == true)
        {
            bool = true;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'City is required when Known city is checked'));
        }
    }
   
    public sample()
    {
        bool = false;
       
    }
     
}