Play Games

Search This Blog

Thursday, January 28, 2016

How to prepare map of map in apex

Apex Code :
Map <id, Map <id,Account>> accountMap = new Map <id, Map <id,Account>> ();
for(Account acc : [select id,name from Account]) {
if(accountMap.containsKey(acc.id)) {
accountMap.get(acc.id).put(acc.id,acc);
} else {
accountMap.put(acc.id, new map <id, Account> {acc.id => acc});
}
}

system.debug('accountMapaccountMap'+accountMap);
Output:


How to deploy/retrieve a visualforce page using package.xml file in salesforce

Assume AccountPage is an apex class in salesforce.
Sample Xml file :
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
 <types>
        <members>AccountPage</members>
  <name>ApexPage</name>
 </types>
    <version>29.0</version>
</Package>

How to deploy/retrieve an Apex Class using package.xml file in salesforce

Assume AccountUpdater is an apex class in salesforce.
Sample Xml file :
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
 <types>
        <members>AccountUpdater</members>
  <name>ApexClass</name>
 </types>
    <version>29.0</version>
</Package>

Wednesday, January 27, 2016

How to deploy/retrieve a custom field using package.xml file in salesforce

How to deploy/retrieve a custom field using package.xml file in salesforce

Assume "Active__c" is a custom field in account object.
Sample Xml file :
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
        <members>Account.Active__c</members>
<name>CustomField</name>
</types>
    <version>29.0</version>
</Package>

Thursday, January 21, 2016

How to call Visualforce Page when a custom button is clicked on standard detail page.

How to call Visualforce Page when a custom button is clicked on standard detail page.

Note: In order to associate particular visualforce page to that custom button,that vf page must use standard controller of that associated object,Otherwise this vf page won't be available in the list while selecting vf page.
Example:
Visualforce Page:
Name: CallingVfPageFromButton
<apex:page>
    This Visualforce Page is getting called when a custom button is clicked on standard Account Detail Page.
</apex:page>
When we try to associate this visualforce page to custom button ,this page won't be available in selection list as shown in below image.

Now modify the above vf page like this
<apex:page standardController="Account">
    This Visualforce Page iss getting called when a custom button is clicked on standard Account Detail Page.
</apex:page>
Now, try to associate this page..this page will be available on the selection list as shown in the image below.

Output: When we click on the custom button in Account record detail page..the vf page will be displayed as shown in the images below.




Testclass for private methods/variables

Testclass for private methods/variables

Solution: Use @TestVisible annotation before private variables/methods of main class.It wonot change any functionality of original class.
Example:
Initial main Apex Class:
public class PrivateMethodDemo {
    private void privateMethod() {
    }
}
In order to write test class for this,first modify this class like below
public class PrivateMethodDemo {
    @TestVisible private void privateMethod() {
    }
}
Now write test class for this
Test class:
@isTest
private class PrivateMethodDemoTest {
    public static testmethod void validate() {
        PrivateMethodDemo demo = new PrivateMethodDemo ();
        demo.privateMethod();
    }
}
Now when we run the test class it will cover all lines of main class.


Error: Compile Error: Method is not visible:

Error: Compile Error: Method is not visible:

We will get this error when we are accessing private methods/variables in test class.
Example:
Apex Class:
public class PrivateMethodDemo {
    private void privateMethod() {
    }
}
Apex Test Class:
@isTest
private class PrivateMethodDemoTest {
    public static testmethod void validate() {
        PrivateMethodDemo demo = new PrivateMethodDemo ();
        demo.privateMethod();
    }
}
When we are saving the above test class,we will get that error.

Solution: Use @TestVisible annotation before private variables/methods of main class.It won't change any functionality of original class.
Modify main class as below
public class PrivateMethodDemo {
    @TestVisible private void privateMethod() {
    }
}
Now save the test class and run.That's it...

Wednesday, January 20, 2016

Difference between insert and Database.insert() in salesforce(difference b/w DML statements and Database class methods).

Difference between insert and Database.insert() in salesforce(difference b/w DML statements and Database class methods).

By using the Database class method(eg.Database.insert()), we can specify whether or not to allow for partial record processing if errors are encountered where as in DML statements(insert) we cannot.
It means eventhough errors are present while doing insert/update/delete operation,if we use Database methods, process will continue where as in DML statements, the process will get stopped and error is thrown away.

How to call apex method when enter key is pressed in visualforce page

How to call apex method when enter key is pressed in visualforce page

Apex Class:
public class EnterKeyEvent {
    public String name {get;set;}
    public void apexMethod() {
        system.debug('Inside Apex Method');
    }

}
Visualforce Page:
<apex:page controller="EnterKeyEvent">
    <script type='text/javascript'>
        function check(ev)  {
            if (window.event && window.event.keyCode == 13 || ev.which == 13) {
                callingApexMethod();
                return false;
             } else {
                  return true;
             }
        }
    </script>
    <apex:form>
        <apex:actionFunction action="{!apexMethod}" name="callingApexMethod"/>
        <apex:inputText value="{!name}" onkeypress="return check(event);"/>
    </apex:form>
</apex:page>
Output:
Enter any text in textbox and then press 'Enter Key'.

Saturday, January 9, 2016

Display SelectList in Visualforce page

Display SelectList in Visualforce page

Apex Code:
public  class SelectList {
    Public String SelectedLocation{get;set;}
    public SelectList (ApexPages.StandardController controller) {

    }
 
    public List<SelectOption> getLocation() {
        List<SelectOption> locationOptions = new List<SelectOption>();
        locationOptions.add(new SelectOption('Hyderabad','Hyderabad'));
        locationOptions.add(new SelectOption('Kolkata','Kolkata'));
        locationOptions.add(new SelectOption('Pune','Pune'));
        locationOptions.add(new SelectOption('Mumbai','Mumbai'));
        locationOptions.add(new SelectOption('Delhi','Delhi'));
        return locationOptions;
    }
}
Visualforce Page:
<apex:page standardController="Account" extensions="SelectList ">
    <apex:form >
        <apex:pageblock >
            <apex:panelGrid columns="5">
                Select City &nbsp;<apex:selectList value="{!SelectedLocation}" multiselect="false" size="1">
                    <apex:selectOptions value="{!Location}"/>
                </apex:selectList>
             </apex:panelGrid>
        </apex:pageblock>
    </apex:form>
</apex:page>
Output:


Scenario Based Interview Questions in Salesforce

Scenario Based Interview Questions in Salesforce

1) You have a page with Standard Controller and one Extension class.In Extenstion class you have a method name called save().Now when your invoking save() method from page whether it will execute Standard Controller save() method or Extension class save() method?
Ans : The Save() method from the Extenstion class will be executed.
2) In a trigger you have addError() method and below that statement you have a System.debug() statement.If addError() method is executed in trigger in that case whether System.debug() statement will be executed or not?
Ans : Yes,Even after addError() method got executed the execution will not be stopped at that line and it will executes below the System.debug() statement also.
3) If in your organisation Person Account feature is enabled.Whenever your converting the Lead how you will decide which Account(Business or Person) to be created?
Ans : Based on the company field value on Lead we will decide whether to create Business Account or Person Account.If Company field value in Lead object is blank then we will create Person account on it's conversion and If Company Field value on Lead object is not blank we will create Business Account
4) How will say particular lead is a Business Lead or Person Lead?
Ans : Based on the company field value on Lead we will decide whether that Lead is Business Lead or Person Lead.If Company Field value is blank then it will be treated as Person Lead,If not it will be treated as Business Lead
5) Lets assume your having a object called Quotes and it is having 4 fields.Now I want to add one extra field to each and every record in Quote object without creating it in Object and I want to display list of Quote records on visual force page with 5 fields not with only 4 fields.
Ans : Whenever your working with these type of scenarios (i.e., Add extra field to each and every record in object actually not creating that field in object) we have to use Wrapper class concept which will add one or more fields for each and every record.
6) When you will end up with MIXED_DML_OPERATION error in Salesforce?
Ans: With in a single transaction if you are trying to perform dml operations on setup objects and non-setup objects with same user(Logged in user) than it throws that error.To avoid that error we need to perform DML on Set up objects with logged in user and on non setup objects with some other user using System.runAs() and vice versa
7) While setting OWD (Organization wide sharing), can we change/modify the setting of child record in case of Master-Detail relationship?
Ans: No, child record is controlled by parent settings.

8) In case of Master-Detail relationship, on Update of child record can we update the field of Parent record using workflow rule?
Ans: Yes, the Master fields are also available for evaluation criteria.So, we can acheive this with workflow.For more information please visit this post

9) How to know the type of a field of an object in apex code?(For example how to get type of AccountSource field of Account object).
Ans: Map<String, Schema.SObjectField> accountFieldMap;
accountFieldMap = Schema.SObjectType.Account.fields.getMap();
Schema.SObjectField field = accountFieldMap.get('AccountSource');
Schema.DisplayType fieldType= field.getDescribe().getType();
system.debug('Type of AccountSource Field :'+fieldType);

Wednesday, January 6, 2016

Get field Type with dynamic apex

Get field Type with dynamic apex

Example:We want to know the type of "AccountSource" field of Account object.
Piece Of Code:
Map<String, Schema.SObjectField> accountFieldMap;
accountFieldMap = Schema.SObjectType.Account.fields.getMap();
Schema.SObjectField field = accountFieldMap.get('AccountSource');
Schema.DisplayType fieldType= field.getDescribe().getType();
system.debug('Type of AccountSource Field :'+fieldType);
Output:

How to call apex method from Javascript in visualforce page

With the help of <apex:actionFunction> tag, we can directly call apex method from javascript.
Apex Class:
public class ClockWatch {
    public integer sec {get;set;}
    public ClockWatch() {
        sec=0;
    }
    public void increment() {
        sec=sec+1;
    }
}
Visualforce Page:
<apex:page controller="ClockWatch" id="page1">
    <script>
        function increment() {
            incrementTimer();
        }
    </script>
    <apex:form id="form1">
        <apex:actionfunction name="incrementTimer" action="{!increment}" />
        <apex:pageBlock id="block1">
            Integer I :   {!sec}<br/>
            <apex:commandButton value="Increment" onclick="increment();" rerender="block1"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Output:

Tuesday, January 5, 2016

How to call apex method from command button in visualforce page


Apex Class:
public class CallApexMethodFromVF {
    public Account acc {get;set;}
    public CallApexMethodFromVF () {
        acc = new Account ();
    }
    public pagereference saveData() {
        insert acc;
        PageReference accountDetailPage = new ApexPages.StandardController(acc).view();
        accountDetailPage.setRedirect(true);
        return accountDetailPage;
    }
}
Visualforce Page :
<apex:page Controller="CallApexMethodFromVF">
    <apex:form >
        <apex:pageBlock title="Account Information" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!saveData}" value="Save Record"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="My Content Section" columns="2">
                <apex:inputField value="{!acc.name}"/>
                <apex:inputField value="{!acc.site}"/>
                <apex:inputField value="{!acc.type}"/>
                <apex:inputField value="{!acc.accountNumber}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Output :
 

Sunday, January 3, 2016

How to delete scheduled job in salesforce

Solution 1:

Step 1: Go to setup --> Jobs  --> Scheduled Jobs.

Here you will find list of all scheduled jobs




Step 2: Select the job to be deleted. Click on the delete Action of the particular job to be deleted.

Here I am deleting "My Job" scheduled job



Solution 2: If you know cronId, then you can abort the scheduled job by executing the following

 line from execute anonymous block

System.abortJob(cronid);





recordSetVar in salesforce

 recordSetVar :The attribute recordSetVar indicates collection of records.This variable can be used to access data in the collection.This attribute is only used with the standard controller.
For example recordSetVar="Accounts" means this variable contains list of account records.
Example:
<apex:page standardController="Account" recordSetVar="Accounts">
    <apex:pageBlock >
        <apex:pageBlockTable value="{!accounts}" var="a">
            <apex:column value="{!a.name}"/>
            <apex:column value="{!a.phone}"/>
            <apex:column value="{!a.accountsource}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>
Output:


How to get Last Modified By Name of a record - Salesforce Globe For You

Apex Piece of Code:
List <Account> accountList = [select id,name,LastModifiedBy.name from Account ];
if(accountList.size() > 0) {
system.debug('LastModifiedByName :'+accountList[0].LastModifiedBy.Name);
}
Output :

Saturday, January 2, 2016

how to display required field as *(STAR) in visualforce page

At First I would like to thank Srinivas for his post on how to display required field as"*".It helped me a lot.Here I am sharing his post so that many of my friends will get benefited from it.
Please go through the link Required Field as star.

How to change required symbol colour in Visualforce Page

Visualforce Page :
<apex:page standardController="Account">
    <style>
    .requiredBlock {
        background-color: yellow !important;
    }
    </style>
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection title="Account Information" collapsible="true">
                <apex:inputField value="{!account.name}" required="true"/>
                <apex:inputField value="{!account.type}" required="true"/>
                <apex:inputField value="{!account.Industry}" required="true"/>
                <apex:inputField value="{!account.rating}" required="true"/>
            </apex:pageBlockSection>
            <apex:pageblockButtons ><apex:commandButton value="Save" action="{!save}"/></apex:pageblockButtons>
        </apex:pageBlock>
    </apex:form>
 </apex:page>
Output :