Sunday, December 11, 2016

Disable button from page layout used in VF page


Disable button from page layout used in VF page


you have used a standard page layout in vf page and you do not want to enable all buttons of that page layout in the VF page always. That means we need to conditionally enable or disable page layout buttons in vf page .

use below tag to display standard layout in VF page
      <apex:detail relatedList="false"></apex:detail>





we need to use javascrcipt or jquery to enable or disable the buttons based on some condition dynamically.

in below code snappet, thisLead is a getter to store the current lead record to show lead information in page.
Here I am disabling Convert button for the leads with status  "Working Converted".  First get the button with getElementByName and set the CSS attribute for the button as Oppacity = 0.65 and cursor as not-allowed.


if ("{!thisLead.Status}" == 'Working - Contacted') {
    var btns = document.getElementsByName('convert');
    for (var i = 0; i < btns.length; i++) {
        btns[i].style.opacity = 0.65;
        btns[i].style.cursor = 'not-allowed';
    }
}

Monday, August 29, 2016

Select All records in Pageblock table Visualforce page Using Javascript



Sometime we are displaying list of records in Visualforce page and need to select some or all by click on check box.
If we need to select all records from the list,we can use client side code(java script) to select all records in a single click instead of selecting each one individually or using some server side code to select all records.

Lets create a VF page where we will display all list of record with a select checkbox.

Visualforce page

<apex:page controller="SelectRecordController">
<!--Javascript to select all records-->
    <script type="text/javascript">
        function selectAllRecords(obj,selInputID){
            var inputCheckBox = document.getElementsByTagName("input");                  
            for(var i=0; i<inputCheckBox.length; i++){          
                if(inputCheckBox[i].id.indexOf(selInputID)!=-1){                                     
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!wrapRecordList}" var="recWrap" id="table" 
                             title="All Accounts">
                <apex:column >
                    <apex:facet name="header">
                        <apex:inputCheckbox onclick="selectAllRecords(this,'inputId')"/>
                    </apex:facet>
                    <apex:inputCheckbox value="{!recWrap.selected}" id="inputId"/>
                </apex:column>
                <apex:column value="{!recWrap.acc.Name}" />
                <apex:column value="{!recWrap.acc.BillingState}" />
                <apex:column value="{!recWrap.acc.Phone}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>



Controller:

public class SelectRecordController {
    public List<wrapRecord> wrapRecordList {get; set;}
     
    public SelectRecordController(){
        if(wrapAccountList == null) {
            wrapRecordList = new List<wrapRecord>();
            for(Account a: [select Id, Name,BillingState, Website, Phone from Account 
                             limit 10]) {                
                wrapRecordList.add(new wrapRecord(a));
            }
        }
    }
     
    public class wrapRecord {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
        
        public wrapRecord(Account a) {
            acc = a;
            selected = false;
        }
    }
}

Output:

When you open this page , all list of records will be displayed with a checkbox in column header.

If you select his check box then JavaScript function will execute and all list of records will be selected.

Monday, August 22, 2016

Create record from CSV file using Apex


Upload Data without DataLoader/Import wizard in salesforce


When there is a need to load data from CSV file to salesforce, generally we use dataloader/jitterbit/import wizard    to import data in salesforce.

while using data loader or import wizard we have to configure some steps like select the object then field mapping etc.

But if there is some requirement to load data by the end user and end user not using data laoader, then we need to develop a functionality to load data using apex and visual force.

Step 1:

Create a standard template and all data should be loaded only by using this standard template

step2:

Save this standard template in Document folder so that All users who are need of it can download.

Step3:

Develop a Vf page which will have Upload csv functionality with a button having the logic to create the record to appropriate object.


Lets explore more on this....


Lets consider I want to develop Lead upload functionality  for the end user, here users are only interested to upload the lead records with field information FirstName, LastName, leadSource, email,company,Phone.

So as per step 1 and 2 , create a CSV  with all these as the header of file as template and store in document folder.

Now develop a VF page where we will have upload lead functionality, here in this page we will have a inputfile component where we will select the csv to upload and one Upload button. On click of the button Lead records will be created in the system and in below we can see the successfully created leads and the leads which are not created in the system due to some error.


Code for VF Page

<apex:page sidebar="false" controller="FileUploader" showHeader="false">
   <apex:form >
      <apex:sectionHeader title="Upload Leads from CSV file"/>
  
      <apex:pageBlock >
             <!--  Component to allow user to upload file from local machine -->
             <center>
              <apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
              <br/> <br/> <font color="red"> <b>Note: Please use the standard template to upload Leads. <a href="/servlet/servlet.FileDownload?file=015O00000016XLt" target="_blank"> Click here </a> to download the template. </b> </font>
             </center> 
    
      <!-- After the user clicks the 'Upload File' button, this section displays the inserted data -->
      <apex:outputText value="leads Created" rendered="{!NOT(ISNULL(uploadedLeads))}"/>
      <apex:pageblocktable value="{!uploadedLeads}" var="lead" rendered="{!NOT(ISNULL(uploadedLeads))}">
          <apex:column headerValue="First Name">
              <apex:outputField value="{!lead.FirstName}"/>
          </apex:column>
          <apex:column headerValue="Last Name">
              <apex:outputField value="{!lead.LastName}"/>
          </apex:column>
          <apex:column headerValue="Lead Source">
              <apex:outputField value="{!lead.leadSource}"/>
          </apex:column>
          <apex:column headerValue="Email">
              <apex:outputField value="{!lead.email}"/>
          </apex:column>
          <apex:column headerValue="Company">
              <apex:outputField value="{!lead.company}"/>
          </apex:column>
        
      </apex:pageblocktable>
        <apex:outputText value="leads Not Created:Due to some error" rendered="{!NOT(ISNULL(NotuploadedLeads))}"/>
       <apex:pageblocktable value="{!NotuploadedLeads}" var="lead" rendered="{!NOT(ISNULL(NotuploadedLeads))}">
          <apex:column headerValue="First Name">
              <apex:outputField value="{!lead.FirstName}"/>
          </apex:column>
          <apex:column headerValue="Last Name">
              <apex:outputField value="{!lead.LastName}"/>
          </apex:column>
          <apex:column headerValue="Lead Source">
              <apex:outputField value="{!lead.leadSource}"/>
          </apex:column>
          <apex:column headerValue="Email">
              <apex:outputField value="{!lead.email}"/>
          </apex:column>
          <apex:column headerValue="Company">
              <apex:outputField value="{!lead.company}"/>
          </apex:column>
        
      </apex:pageblocktable>
    
      </apex:pageBlock>     
   </apex:form> 
</apex:page>


Controller for this Page

public class FileUploader
{
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    String[] filelines = new String[]{};
    List<Lead> leadstoupload;
   // List<Lead> leadsuploaded;
    /***This function reads the CSV file and inserts records into the Lead object. ***/
    public Pagereference ReadFile()
    {
        try{
                //Convert the uploaded file which is in BLOB format into a string
                nameFile =blobToString( contentFile,'ISO-8859-1');
               
                //Now sepatate every row of the excel file
                filelines = nameFile.split('\n');
               
                //Iterate through every line and create a Account record for each row
                leadstoupload= new List<lead>();
                for (Integer i=1;i<filelines.size();i++)
                {
                    String[] inputvalues = new String[]{};
                    inputvalues = filelines[i].split(',');
                   
                    lead l = new lead();
                    l.FirstName = inputvalues[0];
                    l.LastName= inputvalues[1];      
                    l.LeadSource= inputvalues[2];
                    l.Company= inputvalues[3];
                    l.Email = inputvalues[4];
                    l.phone = inputvalues[5];
                    l.Website = inputvalues[6];
                    l.Status = 'Open - Not Contacted';
                    leadstoupload.add(l);
                }
         }
         catch(Exception e){
                 ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,
                               'An error has occured reading the CSV file'+e.getMessage());
                ApexPages.addMessage(errormsg);
         }      
        //Finally, insert the collected records
        try{
            Database.SaveResult[] srList = database.insert(leadstoupload,false);
           
           for (Database.SaveResult sr : srList) {
               if (!sr.isSuccess()) {
              
                   for(Database.Error err : sr.getErrors()) {
                   }

               }

           }

           
           
           
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR, 
                        'An error has occured inserting the records'+e.getMessage());
            ApexPages.addMessage(errormsg);
        }   
        return null;
    }
  
   /**** This function sends back to the visualforce page the list of lead 
     records that were inserted ****/
    public List<lead> getuploadedLeads()
    {
        list<lead> leadscreated;
        if(leadstoupload!=null){
             leadscreated= new list<lead>();
            for(lead l : leadstoupload){
                if(l.id!=null){
                    leadscreated.add(l);
                }
            }
        }
        return leadscreated;
     
           
    } 
     public List<lead> getNotuploadedLeads()
    {
        list<lead> leadsNotcreated;
        if(leadstoupload!=null){
             leadsNotcreated= new list<lead>();
            for(lead l : leadstoupload){
                if(l.id==null){
                    leadsNotcreated.add(l);
                }
            }
        }
        return leadsNotcreated;
     
           
    } 
        /**
         This function convers the input CSV file in BLOB format into a string
        @param input    Blob data representing correct string in @inCharset encoding
        @param inCharset    encoding of the Blob data (for example 'ISO 8859-1')
     */
    public static String blobToString(Blob input, String inCharset){
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
            bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    }        
}


Output:



Create CSV template in below format and add in Document folder, user can download this template and add record information and this updated template with data can  be uploaded to the system by click on Choose file and Upload file button as per the above screen shot.



once you have uploaded lead, you can get the upload result as below screen shot.

Note: I have hard coded document id in above VF page, but we can query this lead template and get the document id whihc we can use inplace of hardcoded id.


Dialog box in Visualforce page


Dialog box in VF page

If we need to show any alert to display in vf page, instead of using window.alert() which is with traditional look and feel, we can use dialog box using below script.

<apex:page >
<script type="text/javascript">
document.body.style.cursor="auto";
var box=new SimpleDialog("This is my alert", true);
box.setTitle("Please initiate call to case contact");
box.createDialog();
    box.setContentInnerHTML("<input type=\"button\" value=\"Ok\"  onclick=\"javascript:box.hide();\"/>");
box.show();
</script>
</apex:page>

Monday, August 1, 2016

Convert a number/Currency to its expression in words

Number To word Converter

Lets consider one scenario where user enters currency in currency/Number format and system need to convert that Currency/number to word format.

ex: $2345.12
Output: USD Two Thousand Three Hundreed Fourty Five and twelve cent.


Create a class NumberToWord 


public  class NumberToWord { 
    static String[] to_19 = new string[]{ 'zero', 'one',  'two', 'three', 'four',  'five', 
 'six', 'seven', 'eight', 'nine', 'ten',  'eleven', 'twelve', 'thirteen', 
     'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' }; 
    static String[] tens = new string[]{ 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 
                               'seventy', 'eighty', 'ninety'}; 
    static String[] denom = new string[]{ '', 
     'thousand',   'million',     'billion',    'trillion',    'quadrillion', 
    'quintillion', 's!xtillion',   'septillion',  'octillion',   'nonillion', 
      'decillion',  'undecillion',   'duodecillion', 'tredecillion',  'quattuordecillion', 
      's!xdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion' }; 
    // convert a value < 100 to English.   
   public static String convert_nn(integer val) { 
      if (val < 20) 
        return to_19[val]; 
     if(val == 100) 
          return 'One Hundred'; 
      for (integer v = 0; v < tens.size(); v++) { 
        String dcap = tens[v]; 
        integer dval = 20 + 10 * v; 
        if (dval + 10 > val) { 
          if (Math.Mod(val,10) != 0) 
            return dcap + ' ' + to_19[Math.Mod(val,10)]; 
          return dcap; 
        }     
      } 
      return 'Should never get here, less than 100 failure'; 
    } 
    // convert a value < 1000 to english, special cased because it is the level that kicks  
    // off the < 100 special case. The rest are more general. This also allows you to 
    // get strings in the form of "forty-five hundred" if called directly. 
    public static String convert_nnn(integer val) { 
      String word = ''; 
      integer rem = val / 100; 
      integer mod = Math.mod(val,100); 
      if (rem > 0) { 
        word = to_19[rem] + ' hundred'; 
        if (mod > 0) { 
          word += ' '; 
        } 
      } 
      if (mod > 0) { 
        word += convert_nn(mod); 
      } 
      return word; 
    } 
    public static String english_number(long val) { 
      if (val < 100) { 
        return convert_nn(val.intValue()); 
      } 
      if (val < 1000) { 
        return convert_nnn(val.intValue()); 
      } 
      for (integer v = 0; v < denom.size(); v++) { 
        integer didx = v - 1; 
        integer dval = (integer)Math.pow(1000, v); 
        if (dval > val) { 
          integer mod = (integer)Math.pow(1000, didx); 
          integer l = (integer) val / mod; 
          integer r = (integer) val - (l * mod); 
          String ret = convert_nnn(l) + ' ' + denom[didx]; 
          if (r > 0) { 
           ret += ', ' + english_number(r); 
          } 
          return ret; 
        } 
     } 
     return 'Should never get here, bottomed out in english_number'; 
   } 
 }



This method not handles for decimal point, so we need to call this class methods twice (once with passing number prior to the decimal point and another one with after decimal point)to convert the currency to word with decimal part .

lets consider I have a currency field test_currency__c in test_ob__c object and i have entered 5678.43 as value for this field.
I want to convert this field value to word format as USD five thousand six hundred seventy eight and fourtyThree cents.


string enteredCurrency = string.valueof(testObj.test_currency__c );
integer decimalIndex= enteredCurrency.indexOf('.');
integer part1=integer.valueof(enteredCurrency.substring(0,decimalIndex));
integer part2=integer.valueof(enteredCurrency.substring(decimalIndex+1));
//Now call the method to convert to word format for number prior to the decimal point
string currencyPart1InWord =  NumberToWord.english_number(part1);
string currencyPart2InWord='';
string amountInWords;
if(part2>0){
       currencyPart2InWord=NumberToWord.english_number(part2);
}
string amountInWords='USD '+currencyPart1InWord;
if(currencyPart2InWord!=null && currencyPart2InWord!=''){
        amountInWords=amountInWords+' and '+ currencyPart2InWord +' cents';
}
amountInWords=amountInWords+' only*';


Now you can get output as USD five thousand six hundred seventy eight and fourtyThree cents.






Friday, July 22, 2016

PageBlock as a Popup in Visualforce

Displaying A section as a Popup in a visulaforce.

when we need to display a popup in visulaforce, used to create a new Vf page with required content to display in popup and that page being opened as a popup page on some event in the page.

But if we need to open a section/Pageblock of a VF page as a popup,How can we do it?



I am using this below code to display the pageblock(Yellow marked) as a popup page.

I have a button(Red Marked)  in the page as "Create New lead" and displaying a popup on click of that button, DIsplaying yellow marked Pageblock as a popup. I have used controller method to set showPopup as True on Click of the create a New Lead button and rerendering the  section to display popup, and all 


Code snippet for Popup


             <apex:form >
                 <apex:sectionHeader title="Create a new Lead"/>
                 <div style="text-align:center">
                 <apex:commandButton value="Create New Lead" action="{!showPopup}" rerender="tstpopup" />
                </div>
                <apex:outputPanel id="tstpopup">
                <apex:outputPanel styleClass="popupBackground" layout="block" rendered="{!displayPopUp}"/>
                    <apex:outputPanel styleClass="custPopup" layout="block" rendered="{!displayPopUp}">
                    <!-- This pageblock being open as Popup-->  
 <apex:pageBlock >
                        <apex:pageBlockButtons >
                            <apex:commandButton action="{!save}" value="Save"/>
                            <apex:commandButton value="Cancel" action="{!closePopup}" rerender="tstpopup" immediate="true"/>
                        </apex:pageBlockButtons>
                        <apex:pageBlockSection >
                             <apex:inputField value="{!leadToCreate.FirstName}" required="true"/>
                             <apex:inputField value="{!leadToCreate.LastName}"/>
                             <apex:inputField value="{!leadToCreate.email}" required="true"/>
                             <apex:inputField value="{!leadToCreate.phone}" required="true"/>
                             <apex:inputField value="{!leadToCreate.company}"/>
                        </apex:pageBlockSection>
                    </apex:pageBlock>
                </apex:outputPanel>
        </apex:outputPanel>
    </apex:form>



Style sheet used in this page:


  <style type="text/css">
        .custPopup{
            background-color: white;
            border-width: 2px;
            border-style: solid;
            z-index: 9999;
            left: 50%;
            padding:10px;
            position: absolute;
            width: 500px;
            margin-left: -250px;
            top:100px;
        }
        .popupBackground{
            background-color:black;
            opacity: 0.20;
            filter: alpha(opacity = 20);
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            z-index: 9998;
        }

    </style>



Controller logic:


public class LeadConsoleController{
    public boolean displayPopup {get; set;}     
    
    public void closePopup() {
       //to ignore required fiedl
          
        displayPopup = false;    
    }     
    public void showPopup() {        
        displayPopup = true;    
    }
    
    public lead leadToCreate{get;set;}
    public LeadConsoleController(){
        leadToCreate = new lead();
    }
    public void save(){
        leadToCreate.ownerId = userinfo.getUserId();
        leadToCreate.status='Open - Not Contacted';
        insert leadToCreate;
        closePopup();
    }
}

















Thursday, July 21, 2016

Enabling TLS1.1 for eclipse-force.com ide


Enabling TLS1.1 for eclipse-force.com IDE

If you use Java 7, you can’t create or edit projects using the Force.com IDE plug-in for Eclipse unless you disable TLS 1.0. (TLS 1.0 is disabled by default in Java 8.)
 Update your eclipse.ini file to include this line.
-Dhttps.protocols=TLSv1.1,TLSv1.2

Open your  eclipse.in from  your eclipse folder as below and add the line "-Dhttps.protocols=TLSv1.1,TLSv1.2" in the end



Thursday, March 10, 2016

salesforce interview questions part3

1. Can we modify records directly in trigger.new ?
Ans: trigger.new is a read only list, but field values can be changed in case of before trigger
2. What does the error "list has no rows for assignment" mean?
Ans: it means the list you are trying to access has no values in it.
3. Why should we not write select query within for loop?
Ans: Writing select query within for loop may hit the governer limit of 100 select queries.
4. What should we do to avoid view state error in visualforce page?
Ans: Clear unused collections, define variable as transient.
5. What is a sandbox org?
Ans: It is the exact copy of your production org.
6. What is sosl?
Ans: select query that can return records of multiple objects as list of lists
7. How many records a select query soql can return?
Ans: as of now the limit is 50000
8. What is the full form of AJAX?
Ans: it stands for assynchronous java and XML
9. Why do we need to write test classes?
Ans: Salesforce does not allow deployment in production if the test coverage is less than 75%
10.How can you show a custom error message in trigger?
Ans: This can be done using addError() method in trigger
11. What is the use of future annotation?
Ans: Future method starts execution when Salesforce has resources available.That is for asynchronous execution.
12. How to identify if a class is a test class?
Ans: test class always begins with @isTest
13. How to convert a blob variable into a string?
Ans Use toString to convert blob into string
14. what are the different methods of batch apex class?
Ans: start method, execute method and finish method
15.What is' with sharing' in apex class code?
Ans: When you use 'with sharing', user's permissions and field-level security are respected. In case of 'without sharing' code runs in system mode.
16. How many records can a sosl return ?
Ans: It can return 2000 records as of now as per governers limit
17. Can you use dml statement in visualforce compoenent controller ?
Ans: To use dml in visualforce component you have to declare allowdml=true in visualforce component otherwise you will get an exception
      "DML is currently not allowed"
18. Can you write sosl in trigger>?
Ans: Earlier this was not allowed but now sosl are allowed in triggers.
19. Which are the different access modifiers in apex?
Ans: 1. Private 2. Public 3. Protected 4.Global are the four access modifiers allowed in apex
20. Can you change the master of a detail record in salesforce ?
Ans. Yes provided you have ticked marked "Allow reparenting" in field setting otherwise the field is read only and master cannot be changed.
21. How can you lock records in apex?
Ans: use For update in query to lock the record. For example: [select id,name from contact limit 10 For update];
22. IS there any limit on the number of items that can be stored in apex collections?
Ans: There is ni such limit but we need to consider heap size limit 6mb (6 MB as of now)
23. How can you monitor future actions of time based workflow?
Ans: setup --> administration set up --> monitoring --> time based workflow
24. What is visaulforce component ?
Ans: It is a piece of code that can be reused. It can be encapsulated in other visualforce pages.
25. Ho can you display the status of an AJAX update request in a visualforce page ?
Ans: To display AJAX request status we can use <apex:actionstatus> component.
26. How can you access custom label in apex:
Ans: Example --> string custLabelstr = System.Label.LabelNamehere
27.How can you get all the keys of a map variable ?
Ans: USe method keyset() for this
     Example = Set<id> idSet = mapname.keyset();
28. How can you compare values of a picklist field in validation rule?
Ans : for comparing picklist value use ispickval
      ISPICKVAL(picklist_field, text_to_compare)
29. What are the different types of sandboxes in salesforce ?
Ans: Developer, Developer Pro, Partial Data and Full are the 4 types of sandboxes in salesforce.
30. With what frequency can you refresh a full copy sandbox?
Ans: full copy sandbox can be refreshed every 29 days from production.
31. How can you make fields required on a visualforce page?
Ans: mark required = true as done in the example below:
     <apex:inputfield value="{!account.Description}" required="true"/>
32. What is minimum coverage for every trigger for deployment?
Ans: every trigger should have a minimum coverage of 1%. Total coverage should be 75%
33. What is minimum coverage for every class for deployment?
Ans: There is no such requirement. A class can have 0% but the total coverage should be >75%
34. How can you implement custom functionality for a standardcontroller visualforce page?
Ans: This can be done by associating a controller class with that standard controller using "Extenssions"
35. How can you get the current record id in a visualforce page ?
Ans use ApexPages.CurrentPage().getparameters().get('id') to get the current record id in visaulforce page.
36. Can a user change his own profile in salesforce ?
Ans: No, a user cannot change change his own profile !!
37. Can a user change his own role?
Ans: Yes this can be done !!
38. Reset security token option is unavailabel in set up. What could be the reason?
Ans: If in the profile setting "login ip ranges" have been set up then the option of "reset security token" is uanvailbale.
39. How can you skip record type selection page(and take up default record type) while creating new record of a aprticular object ?
Ans: just tickmark against the object by navigating to following :
     set up --> my personal information -- > Record type selection --> check against the required object
40. What are the different data types that a standard field record name can have?
Ans: Record name field can have either of the two data types : Auto Number or Text data type
41. Can you edit a apex trigger/apex class in production environment ?
Ans: No apex trigger /class cannot be edited in production.
42. Can you edit a visuaflorce apge in production environment ?
Ans: Yes this can be done.
43.How can you deliver a visualforce page in excel form ?
Ans: use contentType="application/vnd.ms-excel#Contacts.xls" in page component of visualforce page
44. What is trigger.new?
Ans: It is a list of records in current context in a trigger.
45. What does it mean when you get the error "too many soql queries 101 salesforce"
Ans: It means you are hitting the limit of 100 soql queries as per governers limit
46. How can you create a input field for date on a visualforce page ?
Ans: To create a input date field on vf page you will have to bind it with a existing date field on any object.
47. How can you convert a text to upper string ?
Ans: stringname.toUppercase();
48. How can you convert a integer into a string ?
Ans: string.valueof(integerName);
49. What are the different types of email templates that can be created in salesforce?
Ans: Text, HTML (using Letterhead), Custom (without using Letterhead) and Visualforce.
50. How can you display different picklist values for picklist fields in different page layouts?
Ans: This can be done using record types.

Salesforce interview question part2

1. For which criteria in workflow "time dependent workflow action" cannot be created?
    Ans: created, and every time it’s edited
2. What is the advantage of using custom settings?
     Ans : You dont have to query in apex (fire select query) to retrieve the data stored in custom settings.
3. What are the different workflow actions available in workflows?
     Ans: 1. Field update 2. Email alert 3. send Outbound messages 4. Create new task
4. What is whoid and whatid in activities?
    Ans: Whoid is the id of either contact or Lead. Whatid is the id of the related to record in activity record(standard or custom object)
5. What is the difference between a standard controller and custom controller
     Ans: standard controller inherits all the standard object properties, standard button functionalities can be directly used. Custom controller defines custom functionalities, a standard controller can be extended to develop custom functionalities using keyword "extenssions"
6. Can you have more than one extenssions associated with a single page?
     Ans : Yes we can have more than extenssions.
7. If page is having multiple extenssions and if two extenssions have methods of same name.     Then which method out of these two will be called upon calling from vf page ?
  Ans: The one which is present in the controller defined on the left side will be called.
8. What are governer limits ?
     Ans: Governer limits are the limits imposed by salesforce so as to avoid monopoly by orgs in using salesforce shared resources.
9. how can we implement pagination in visualforce ?
    Ans: use standardset controllers for implementing pagination.
10. What is the difference between force.com and salesforce.com
       Ans: force.com is paas(platform as a service) and salesforce.com is Saas(software as a service)
11. What is a externalid in salesforce
       Ans: It is a field which can be used to store a value that is used as a refernce for that record in other system. For example if you have a record in system 'xyz' where it is referenced by some value then that value can be used as external id in salesforce for that record. External id can be used for upsert operation in data loader
12. What happens upon lead conversion ?
       Ans: When lead is converted a contact, account and optionally an opportunity is created.
13. What are different ways of deployment in salesforce ?
       Ans: Change sets, eclipse and ANT
14. How can you override a list button with a visuaflorce page?
       Ans: Visualforce page should be a list controller that is it should have "recordsetVar" attribute defined in page tag.
15. Is it possible to bypass Grant Access Using Hierarchies in case of standard objects ?
      Ans : No. This is default and cannot be changed.
How can you call a controller method from java script ?
Ans: Use action function component to call controller method from java script.
17. How can you call a visualforce page from a controller method?
Ans: Use pagereference object for calling a visualforce page from controller method
18. How can you sort a select SOQl query ?
Ans: use order by clause in select query for sorting a list of records
19. How much code coverage is needed for deployment?
Ans : Each trigger should have minimum of 1%. Class can have 0%. But, the total code covergae of 75%.
20. Can 'set' store duplicate values in it?
Ans : No. Set only stores unique values. List can have duplicate values in it.
21. Can two users have same profiles?
Ans: Yes
22. How can you refresh a particular section of a  visualforce page?
Ans: This can be done using reRender attribute 
23. How can you create a many to many relationship in salesforce
Ans: This can be done by creating junction object between the two objects.
24. What happens to detail record when a master record is deleted?
Ans: detail record gets deleted.
25. What happens to child record when a parent record is deleted(look up relationship)?
Ans. Child record remains undeleted 
26. How to get current logged in users id in apex ?
Ans: Use Userinfo.getuserid() to get the current logged in user's id in apex.
27. How to convert a csv file  browsed in visualforce page into a string.
Ans: use csvfilecontents.tostring(). method to convert blob to string
28.How many records can a select query return ?
Ans : As of now it can return upto 50000 records.
29. How many records can a sosl query return ?
Ans: as of now it can return upto 2000 records
30. How to fire dynamic query in soql?
Ans: Using database.query
     Example: List<account> accList = Database.query('select name from account');
What is a bucket field in reports?
Ans: This field is used for custom grouping of values in a field. This can be used in summarising the report.
32. What are dynamic dashboards ?
Ans: Dashboards which run for logged in user are dynamic dashboards
33. Can the dynamic dashboards be scheduled?
Ans: No they cannot be scheduled.
34.How can you use custom label; in visualforc page?
Ans: Use this syntex for accessing custom albel in visualforce page - {!$Label.Samplelabel}
35.What are the types of custom settings in salesforce?
Ans: List type and Heirarchy type
36.What are the different types of collections in apex?
Ans: There are three types of collections in apex language
     1. Set
     2. List
     3. Map
37. What are maps in apex?
Ans: Map has keys and values. A key points to a single value. Map can be used to store realationship between two entities. Keys in map are unique. Values can be duplicated.
38. What are the different types of object relations in salesforce ?
Ans: 1. One to many
     2. Many to many
     3. Master detail
39.Can you have roll up summary fields in case of parent child relationship?
Ans: No. These are present only in case of master details relationship.
40. Can you see a lead which is converted in saleforce UI?
Ans: The detail record is not seen. But a page, wherein it shows the links for formed account, contact and opportunity.
41. What is the difference between action function and action support ?
Ans: Action functions can call controller method from java script, action support adds support to other components.
42. What is action poller in visualforce ?
Ans: Action poller sends AJAX request with a specified time interval.
43. What are the different types of reports available in salesforce?
Ans: 1. tabular report
     2. Summary Report
     3. Matrix Report
     4. Joined Report
44. How many active assignments rule can you have in lead/Case?
Ans: You can have only one active assignment rule at a time
45. How do we access static resource in visualforce?
Ans: Use this syntex for accessing static resource {!$Resource.Testresourcename}
46. How to embed a visaulflow in a visualforce page ?
Ans: Use this syntex to embed flow in vf page : <flow:interview />
47. How to enable inline editing in visauflorce page ?
Ans You can enable inline editing in visualforce page by using <apex:inlineEditSupport> component.
48. What is trigger.new in trigger ?
Ans: trigger.new is a list of records that are in the context of trigger or becuase of these records(modification,Creation, deletion) the trigger has been called
49. How do we bulkify the trigger ?
Ans: Bulkfification requires iterating over all the records in trigger context
     for example : for(account ac: trigger.new){
                       // your logic here           
                   }
50.How can we get the old value in trigger ?
Ans: use trigger.old map for getting previous values of fields.