How to get Account's State, City, Country fields in Visualforce page?

Billing Address Fields:
  1. BillingStreet
  2. BillingCity
  3. BillingCountry
  4. BillingState
  5. BillingPostalCode
Sample SOQL:

SELECT BillingStreet, BillingCity, BillingCountry, BillingState, BillingPostalCode FROM Account

How to track more than 20 fields values in Salesforce?

Write a tirgger and create a Chatter feed.

Sample Trigger:

trigger FieldHistory on Member__c (after insert, after update) {
    Map<Id, Member__c> MemberMap = trigger.oldMap;
    List<FeedItem> FIList = new List<FeedItem>();
    if(trigger.isInsert) {       
        for(Member__c Mem : trigger.new) {
            FeedItem FI = new FeedItem();
            FI.Body = 'Member Created';
            FI.ParentId = Mem.Id;
            FIList.add(FI);
        }
        insert FIList;
    }
    if(trigger.isUpdate) {
        for(Member__c Mem : trigger.new) {
            Member__c OldMem = new Member__c();
            OldMem = MemberMap.get(Mem.Id);
            if(Mem.Area__c != OldMem.Area__c) {
                FeedItem FI = new FeedItem();
                FI.Body = 'Area changed from ' + OldMem.Area__c + ' to ' + Mem.Area__c;
                FI.ParentId = Mem.Id;
                FIList.add(FI);
            }
        }
        if(!FIList.isEmpty()){
            insert FIList;
        }       
    }
}


Output:



How to refresh Apex variable inside Javascript?

Workaround:

Move the Javascript inside apex:outputPanel and rerender the apex:outputPanel to refresh Apex variable inside Javascript.

Don't keep the Javascript snippet in the beginning of the page, move it to the last before </apex:page> tag.

Sample Code:

<apex:page> 

<apex:pageBlock>
   /*...........................
    Your VF page code here


    ..........................*/
</apex:pageBlock>

<apex:outputPanel id="jspanel">
    <script type="text/javascript">
        function cancl()
        {
            Check = "{!flag}";
            if(Check == "true")
            {
                var pid='{!$CurrentPage.parameters.pid}';
                top.location=window.location.protocol + '//' + window.location.host+'/'+pid;
            }   
        }
    </script> 
</apex:outputPanel>

</apex:page>

here flag is an Apex variable.

Test Class for Batch Apex in Salesforce

Sample Batch Class:


Test class for above Batch Class:
@isTest
public class AccountUpdateTest {
    static testMethod void test() {
        Database.QueryLocator QL;
        Database.BatchableContext BC;
        List<Account> AcctList = new List<Account>();
        AccountUpdate AU = new AccountUpdate('Name', 'Test');
        QL = AU.start(bc);
       
        Database.QueryLocatorIterator QIT =  QL.iterator();
        while (QIT.hasNext())
        {
            Account Acc = (Account)QIT.next();           
            System.debug(Acc);
            AcctList.add(Acc);
        }       
       
        AU.execute(BC, AcctList);
        AU.finish(BC);       
    }
}

How to store value checked by checkbox ( on the VF page ) in the database with controller?

Sample Code:

Visualforce page:

<apex:page controller="Sample">
<apex:form >
    <apex:pageblock >
        <apex:pageBlockSection >
            <apex:panelGrid columns="2">
                Name :
                <apex:inputText value="{!Nam}"/>
                Skilled :
                <apex:inputCheckbox value="{!Skilled}"/>
            </apex:panelGrid>           
        </apex:pageBlockSection>
        <apex:commandButton value="Save" action="{!sav}"/>
    </apex:pageblock>
</apex:form>
</apex:page>

Apex Controller:

public class Sample { 
    public String Nam {get;set;}
    public Boolean Skilled {get;set;}
    Integer n = 5;
    public List<Member__c> MemList {get;set;}
    public Sample() {
       
    }
    public void sav() {
        Member__c Mem = new Member__c();
        Mem.Name = Nam;
        Mem.Skilled__c = Skilled;
        insert Mem;
    }          
}

How to give SOQL limit size dynamically for retrieving records using Apex in Salesforce?

Sample Code:

Visualforce page:

<apex:page controller="Sample">
<apex:form >
    <apex:pageblock >
        <apex:pageBlockTable value="{!MemList}" var="M">
            <apex:column value="{!M.Name}"/>
        </apex:pageBlockTable>
    </apex:pageblock>
</apex:form>
</apex:page>

Apex Controller:

public class Sample {  
    Integer n = 5;
    public List<Member__c> MemList {get;set;}
    public Sample() {
    /* We can write like this too
        MemList = [SELECT Name FROM Member__c LIMIT : n];
    */
        String Soql = 'SELECT Name FROM Member__c LIMIT ' + n;
        MemList = Database.query(Soql);
    }           
}

Output:


How open in new Tab for PageReference?

To open the URL in new Tab for PageReference, kindly use <apex:commandLink/>.

Sample Code:

Visualforce page:

<apex:page controller="Sample">
<apex:form >
    <apex:pageblock >
        <apex:commandlink action="{!switch}" target="_blank">
            <apex:commandButton value="Switch"/>
        </apex:commandLink>
    </apex:pageblock>
</apex:form>
</apex:page>


Apex Controller:

public class Sample {  
   
    public Sample() {
    }
   
    public pageReference switch() {
        PageReference pageRef = new PageReference('http://www.google.com');
        pageRef.setRedirect(true);
        return pageRef;
    }           
}

Force.com Migration Tool

The Force.com Migration Tool is a Java/Ant-based command-line utility for moving metadata between a local directory and a Salesforce organization.

The Force.com Migration Tool is especially useful in the following scenarios:
• Development projects where you need to populate a test environment with large amounts of setup changes
• Multistage release processes
• Repetitive deployment using the same parameters
• When migrating from stage to production is done by IT

Link for more information,

http://www.salesforce.com/us/developer/docs/daas/salesforce_migration_guide.pdf

Cheers!!!

How to get Date from DateTime field using Apex in Salesforce?

Date() is used to get the date from datetime field.


Sample Code:

Datetime LastModifiedDateTime = Datetime.now();  
Date ModifiedDate = LastModifiedDateTime.Date();

Trigger to capture Deactivation of User date

Sample Code:

trigger DeactivationDate on User (before update) {
    Map<Id, User> UserMap = trigger.oldMap;
   
    for(User U : trigger.new) {
        if(U.IsActive == false) {
            User Usr = UserMap.get(U.Id);
            if(Usr.IsActive == true) {
                U.Deactivation_Date__c = U.LastModifiedDate;
            }          
        }
    }
}

Trigger to count number of Contacts associated with an Account

Sample Trigger:

trigger ContactCount on Contact (after insert, after update, after delete, after undelete) {
    Map<Id, List<Contact>> mapAcctIdContactList = new Map<Id, List<Contact>>();
    Map<Id, List<Contact>> mapAcctIdDelContactList = new Map<Id, List<Contact>>();
    Set<Id> AcctIds = new Set<Id>();    
    List<Account> listAcct = new List<Account>();
    
    if(trigger.isInsert) {
        for(Contact Con : trigger.New) {
            if(String.isNotBlank(Con.AccountId)) {
                if(!mapAcctIdContactList.containsKey(Con.AccountId)) {
                    mapAcctIdContactList.put(Con.AccountId, new List<Contact>());
                }
                mapAcctIdContactList.get(Con.AccountId).add(Con); 
                AcctIds.add(Con.AccountId);
            }   
        }  
    }
    
    if(trigger.isUpdate) {
        for(Contact Con : trigger.New) {
            if(String.isNotBlank(Con.AccountId) && Con.AccountId != trigger.oldMap.get(Con.Id).AccountId) {
                if(!mapAcctIdContactList.containsKey(Con.AccountId)){
                    mapAcctIdContactList.put(Con.AccountId, new List<Contact>());
                }
                mapAcctIdContactList.get(Con.AccountId).add(Con); 
                AcctIds.add(Con.AccountId);
            } else if(String.isBlank(Con.AccountId) && String.isNotBlank(trigger.oldMap.get(Con.Id).AccountId)) {
                if(!mapAcctIdDelContactList.containsKey(Con.AccountId)){
                    mapAcctIdDelContactList.put(Con.AccountId, new List<Contact>());
                }
                mapAcctIdDelContactList.get(Con.AccountId).add(Con);   
                AcctIds.add(trigger.oldMap.get(Con.Id).AccountId);
            }
        }  
    }
    
    if(trigger.isUndelete) {
        for(Contact Con : trigger.new) {
            if(String.isNotBlank(Con.AccountId)){
                if(!mapAcctIdContactList.containsKey(Con.AccountId)){
                    mapAcctIdContactList.put(Con.AccountId, new List<Contact>());
                }
                mapAcctIdContactList.get(Con.AccountId).add(Con);     
                AcctIds.add(Con.AccountId);
            }
        }  
    }      

    if(trigger.isDelete) {
        for(Contact Con : trigger.Old) {
            if(String.isNotBlank(Con.AccountId)){
                if(!mapAcctIdDelContactList.containsKey(Con.AccountId)){
                    mapAcctIdDelContactList.put(Con.AccountId, new List<Contact>());
                }
                mapAcctIdDelContactList.get(Con.AccountId).add(Con);    
                AcctIds.add(Con.AccountId); 
            }
        }  
    }   
    
    if(AcctIds.size() > 0) {
        listAcct = [SELECT Id, Number_of_Contacts__c FROM Account WHERE Id IN : AcctIds];
        
        for(Account acct : listAcct) {
            Integer noOfConts = 0;
            if(mapAcctIdContactList.containsKey(acct.Id)) {
                noOfConts += mapAcctIdContactList.get(acct.Id).size();
            }
            if(mapAcctIdDelContactList.containsKey(acct.Id)) {
                noOfConts -= mapAcctIdDelContactList.get(acct.Id).size();
            }
            acct.Number_of_Contacts__c = acct.Number_of_Contacts__c == null ? noOfConts : (acct.Number_of_Contacts__c + noOfConts);
        }
        
        update listAcct;    
    }
}

Cheers!!!

How to write test class for Database.QueryLocator in Batch Apex?

Sample Batch Class:



Test class for above Batch Class:

@isTest
public class AccountUpdateTest {
    static testMethod void test() {
        Database.QueryLocator QL;
        Database.BatchableContext BC;
        List<Account> AcctList = new List<Account>();
        AccountUpdate AU = new AccountUpdate('Name', 'Test');
        QL = AU.start(bc);
       
        Database.QueryLocatorIterator QIT =  QL.iterator();
        while (QIT.hasNext())
        {
            Account Acc = (Account)QIT.next();           
            System.debug(Acc);
            AcctList.add(Acc);
        }       
       
        AU.execute(BC, AcctList);
        AU.finish(BC);       
    }
}

Test Class for Batch Class

Sample Batch Class:


Test class for above Batch Class:

@isTest
public class AccountUpdateTest {
    static testMethod void test() {
        Database.QueryLocator QL;
        Database.BatchableContext BC;
        List<Account> AcctList = new List<Account>();
        AccountUpdate AU = new AccountUpdate('Name', 'Test');
        QL = AU.start(bc);
       
        Database.QueryLocatorIterator QIT =  QL.iterator();
        while (QIT.hasNext())
        {
            Account Acc = (Account)QIT.next();           
            System.debug(Acc);
            AcctList.add(Acc);
        }       
       
        AU.execute(BC, AcctList);
        AU.finish(BC);       
    }
}

Address Field in Lead object

Address Field in Lead object are

1. Street
2. State
3. PostalCode 
4. Country

Regular Expression for numbers alone validation in Salesforce

Sample Formula:

NOT( REGEX( Miscallaneous__c , '[0-9]*' ) )

Cheers!!!

How to display current date and time in a field using formula field?

Now() is used to display current date and time in a field using formula field.

How to display current date in a field using formula field?

Today() is used to display current date in a field using formula field.

How to assign Permission Set to multiple users?

In order to assign Permission Set to multiple users, try the below AppExchange tool,

https://appexchange.salesforce.com/listingDetail?listingId=a0N3000000B4GsTEAV

Cheers!!!

Sample Screenshots:




Cheers!!!

How to check whether a list is empty or not in Visualforce page in Salesforce?

Sample Code:

        <apex:outputPanel style="visibility:{! IF(ISNULL(PGList), 'hidden', 'visible') }">
            <apex:outputText styleClass="bld" value="Public Group(s) :"/><br/>
            <apex:pageBlockTable value="{!PGList}" var="PG">
                <apex:column value="{!PG.Name}"/>
            </apex:pageBlockTable> 
        </apex:outputPanel>


here PGList is a list variable.

How to customize search settings in Salesforce?

1. Go to Setup --> Build --> Customize --> Search --> Search Settings.




How to create Event using Apex in Salesforce?

Sample Code:

    Event E = new Event();
    E.Type = 'Email';
    E.Description = ''; //string
    E.OwnerId = ''; //user id
    E.WhatId = ''; //record id
     insert E;

How to create Task using Apex in Salesforce?

Sample Code:

    Task T = new Task();
    T.Type = 'Email';
    T.Description = ''; //string
    T.OwnerId = ''; //user id
    T.WhatId = ''; //record id
     insert T;


Cheers!!!

Date and DateTime methods in Salesforce

Sample Code:

        System.debug('Current Year is ' + Date.Today().Year());   
        System.debug('Current Month is ' + Date.Today().Month());
        System.debug('Current Day is ' + Date.Today().Day());
        System.debug('Yesterday Date is ' + Date.Today().addDays(-1));        
        System.debug('Tomorrow Date is ' + Date.Today().addDays(1)); 
        System.debug('Today Date and time is ' + DateTime.Now());

Output:


Connected Apps in Salesforce

A "Connected App" is an application that can connect to salesforce.com over Identity and Data APIs. Connected Apps use the standard OAuth 2.0 protocol to authenticate, provide Single Sign-On, and acquire access tokens for use with Salesforce APIs. In addition to the standard OAuth capabilities supported by the existing Remote Apps feature (which Connected Apps is designed to replace), Connected Apps add additional levels of control, allowing administrators explicit control over who can use the application, and various security policies to be enforced by the application.

To view the list of connected Apps in your organization, go to Setup --> Build --> Create --> Apps --> Connected Apps.


How to get the currency symbol in Visualforce page?

Use <apex:outputField/> to show the currency symbol, instead of using <apex:outputText/>.
Sample Code:

Visualforce page:

<apex:page controller="Sample">
    <apex:pageblock >
        <apex:pageBlockTable value="{!OpptyList}" var="O">
            <apex:column value="{!O.Name}"/>
            <apex:column >
                <apex:outputField value="{!O.Amount}"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageblock>
</apex:page>


Apex Controller:

public class Sample {  
    public List<Opportunity> OpptyList {get;set;}
   
    public Sample() {
        OpptyList = [SELECT Name, Amount FROM Opportunity];
    }           
}


Output:


sObjects that don’t Support DML Operations

These objects doesn't support DML operations from Apex, but it supports SOQL(Querying)
  1. AccountTerritoryAssignmentRule
  2. AccountTerritoryAssignmentRuleItem
  3. ApexComponent
  4. ApexPage
  5. BusinessHours
  6. BusinessProcess
  7. CategoryNode
  8. CurrencyType
  9. DatedConversionRate
  10. ProcessInstance
  11. Profile
  12. RecordType
  13. SelfServiceUser
  14. StaticResource
  15. UserAccountTeamMember
  16. UserTerritory
  17. WebLink

DML requires SObject or SObject list type: LIST

With the Winter '12 release, Salesforce.com support APEX SOQL only (not DML) across the Assignment and Permission set objects which includes User Permisions :(

To know other standard objects which doesn't support DML operations, kindly use the link below

http://www.infallibletechie.com/2013/09/sobjects-that-dont-support-dml.html

How to get all Public Groups using Apex in Salesforce?

Sample Code:

List<Group> TempPGList = new List<Group>();

String SOQL = 'SELECT Id, Name FROM Group WHERE Type = \'Regular\'';
TempPGList = Database.Query(SOQL);

How to check whether a field value is null or blank in Visualforce

Sample Code:

Visualforce page:

<apex:page controller="Sample">
    <apex:pageblock >
        <apex:pageBlockTable value="{!MembList}" var="M">
            <apex:column value="{!M.Name}"/>
            <apex:column >
                <apex:outputText value="{! IF((M.Age__c == null), 'NA', M.Age__c) }"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageblock>
</apex:page>


Apex Controller:

public class Sample {  
    public List<Member__c> MembList {get;set;}
   
    public Sample() {
        MembList = [SELECT Name, Age__c FROM Member__c];
    }           
}


Output:

How to check whether a field value in visualforce page is blank or null?

Sample Code:

Visualforce page:

<apex:page controller="Sample">
    <apex:pageblock >
        <apex:pageBlockTable value="{!MembList}" var="M">
            <apex:column value="{!M.Name}"/>
            <apex:column >
                <apex:outputText value="{! IF((M.Age__c == null), 'NA', M.Age__c) }"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageblock>
</apex:page>


Apex Controller:

public class Sample {  
    public List<Member__c> MembList {get;set;}
   
    public Sample() {
        MembList = [SELECT Name, Age__c FROM Member__c];
    }           
}


Output:



How to enable Opportunity split in Salesforce?

1. Go to Setup --> Build --> Customize --> Opportunity --> Opportunity Team.


2. Enable Team Selling.


3. Select the Page Layouts.


4. Go to Setup --> Build --> Customize --> Opportunity --> Opportunity Team --> Opportunity Splits.



5. Enable Opportunity Splits.


6. Select the Page Layouts.


7. Open an opportunity with team members associated with it.

8. Click "Edit Opportunity Splits" button.


9. Enter the details and click "Save" button.


Output:



Opportunity split in Salesforce

With Opportunity Splitting it is possible to split credit for an Opportunity across multiple users. Reports can also be created using these information.

1. Go to Setup --> Build --> Customize --> Opportunity --> Opportunity Team.


2. Enable Team Selling.


3. Select the Page Layouts.


4. Go to Setup --> Build --> Customize --> Opportunity --> Opportunity Team --> Opportunity Splits.


5. Enable Opportunity Splits.


6. Select the Page Layouts.


7. Open an opportunity with team members associated with it.

8. Click "Edit Opportunity Splits" button.


9. Enter the details and click "Save" button.


Output:


Scatter Charts in Salesforce

Plot two numerical summaries against one another to visualize the correlation between values for a particular grouping on a report.

Use scatter charts to show meaningful information using one or two groups of report data plus summaries.



Cheers!!!

Difference between managed and unmanaged package in Salesforce



Unmanaged Package
Managed Package
Unmanaged packages are typically used to distribute open-source projects or application templates to provide developers with the basic building blocks for an application.
Managed packages are typically used by salesforce.com partners to distribute and sell applications to customers.
Once the components are installed from an unmanaged package, the components can be edited in the organization they are installed in.
Once the components are installed from a managed package, the components cannot be edited in the organization they are installed in.

Cheers!!!

How to reset a visualforce page in Salesforce?

Sample Code:

Visualforce page:

<apex:page controller="Sample">
<apex:form >
    <apex:pageBlock >
        <apex:panelGrid >
            Name: <apex:inputtext />
            Age: <apex:inputtext />
            Addres: <apex:inputTextarea />                       
        </apex:panelGrid>
        <apex:pageBlockButtons >
            <apex:commandButton value="Reset" action="{!reset}"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>   
</apex:page>


Apex Controller:

public without Sharing class Sample {
    public Sample() {
    }
    public PageReference reset() {
        PageReference pg = new PageReference(System.currentPageReference().getURL());
        pg.setRedirect(false);
        return pg;
    }
}

How to avoid Time Zone issue in Apex in Salesforce?

Workaround to avoid Time Zone issue in Apex in Salesforce

        Date Dat = Date.Today();//here you can pass your date
        Date dt = Dat.dateGmt();
        Time tm = Dat.timeGmt();
        Datetime result = Datetime.newInstanceGmt(dt, tm); 

How to get the current User time zone in an Apex class?

UserInfo.getTimeZone() is used to get the current User time zone in an Apex class

TimeZone tz = UserInfo.getTimeZone();

How to get the current User ID in an Apex class?

UserInfo.getUserId() is used to get the current User ID in an Apex class.

String Uid = UserInfo.getUserId();

newInstanceGmt in Salesforce

Constructs a DateTime from the specified date and time in the GMT time zone.

Sample Code:

        Date Dt = Date.today();
        Integer yr = Dt.year();
        Integer mon = Dt.month();
        Integer dy = Dt.day();
        Datetime result = Datetime.newInstanceGMT(yr, mon, dy);


How to enable Chatter Approvals in Salesforce?

1. Go to Setup --> Build --> Customize --> Chatter --> Settings.


2. Check whether Allow Approvals check box under Approval Posts is checked.


3. Go to Home page by clicking "Home" tab and view the post to Approve/Reject.


Output:

Before Approval:


After Approval:


How to get current month using apex in Salesforce?

Sample Code:

Integer Month = Date.Today().Month();

How to get current year using apex in Salesforce?

Sample Code:

Integer Year = Date.Today().Year();

How to calculate hour ranges using apex in Salesforce?

Sample Trigger:

trigger MemberSample on Member__c (before insert, before update) {
    for(Member__c mem : trigger.New) {
        Double var = Math.Floor((Double.valueOf(mem.End__c.getTime()) - Double.valueOf(mem.Start__c.getTime())) / (1000.0*60.0*60.0));
        mem.Description__c = String.valueOf(var);
    }

How to find difference between time in Salesforce?

Sample Trigger:

trigger MemberSample on Member__c (before insert, before update) {
    for(Member__c mem : trigger.New) {
        Double var = Math.Floor((Double.valueOf(mem.End__c.getTime()) - Double.valueOf(mem.Start__c.getTime())) / (1000.0*60.0*60.0));
        mem.Description__c = String.valueOf(var);
    }
}

How to delete scheduled Batch Class in Salesforce?

1. Go to Monitor --> Jobs --> Scheduled Jobs.


2. Delete the appropriate scheduled job.


How to delete scheduled Data Export in Salesforce?

1. Go to Monitor --> Jobs --> Scheduled Jobs.


2. Delete the appropriate scheduled job.


API Currently Disabled Error in Saelsforce

In the user profile, kindly select "API Enabled" check box.


Field Update Workflow in Salesforce

1. Go to Setup --> Build --> Create --> Workflows and Approval Process --> Workflow Rules.


2. Click "New Rule".


3. Select Object and click "Next" button.


4. Enter Name, Evaluation Criteria and Rule criteria.

5. Click "Save and New".


6. Click "New Field Update".


7. Enter Name, Description, Field to update and value to be updated.


8. Activate the Workflow Rule.


Sample Output: