anusha(salesforce developer)

Most commonly used code snippets

201. Common Apex page attributes.
1<apex:page sidebar="false" standardStylesheets="false" showHeader="false">
202. Declare Visualforce page as HTML5.
1<apex:page docType="html-5.0" />
203. Visualforce page output as JSON.
1<apex:page controller="ControllerName"  contentType="application/x-JavaScript; charset=utf-8"showHeader="false" standardStylesheets="false" sidebar="false">
2{!jsonString}
3</apex:page>
204. How to refer static resources in Visualforce.
CSS File :
1<apex:stylesheet value="{!URLFOR($Resource.style_resources, 'styles.css')}"/>
Relative path in CSS from static resource, You can use relative paths in files in static resource archives to refer to other content within the archive.
1table { background-image: img/testimage.gif }
Image tag:
1<apex:image url="{!$Resource.TestImage}" width="50" height="50"/>
or
1<apex:image url="{!URLFOR($Resource.TestZip, 'images/Bluehills.jpg')}" width="50" height="50"/>
Include Javascript in Visualforce from Static resource
1<apex:image url="{!$Resource.TestImage}" width="50" height="50"/>
Refer static resource path from Aprx Controller
1global class MyController {
2    public String getImageName() {
3        return 'Picture.gif';//this is the name of the image
4    }
5}
1<apex:page renderAs="pdf" controller="MyController">
2    <apex:variable var="imageVar" value="{!imageName}"/>
3    <apex:image url="{!URLFOR($Resource.myZipFile, imageVar)}"/>
4</apex:page>
205. How to get element id of Visualforce components to be used in Javascript ?
1{!$Component.Parent1.Parent2.fieldId}
206. Autogenerated Salesforce Id consist of colon, how to handle it in JQuery ?
1var ele = $('[id="abc:xyz"]');
207. How to return Map result from SOQL query in Apex.
1Map<ID, Contact> m = new Map<ID, Contact>([SELECT Id, LastName FROM Contact]);
208. How to query and abort scheduled job using Apex.
While updating class on Sandboxes, chances are high that it is being used in any scheduler, so below code will abort all scheduled job. If there are 150+ scheduled job, then you might want to use below code again and again in developer console until all jobs are removed from system.
1//Limit is 150 because System.abortJob counted against DML
2List<CronTrigger> abort_job = [SELECT Id FROM CronTrigger WHERE State != 'Deleted' limit 150];
3    for (CronTrigger t : abort_job) { //for each record
4     //try catch - to make sure one fail should not impact other jobs which needs to be cancelled
5     try{
6        System.abortJob(t.Id); //abort the job
7     }catch(Exception e){}
8      
9    }
209. How to use standard Salesforce REST API from Visualforce page ?
Befor any Ajax call, make sure to add ‘Bearer’ token in header. If using JQuery use below code snippet. For more information read this post.
1$.ajax({
2          type: reqType,
3          beforeSend: function (xhr)
4                {
5                    xhr.setRequestHeader("Authorization",  'Bearer {!$API.Session_ID}');
6 
7                },
8          headers : {'Content-Type' 'application/json; charset=utf-8'},
9          url: postUrl,
10          data: postData,
11          dataType: 'text'
12        })
13         .done(function( data ) {
14                //Code if success
15          })
16          .fail(function(xhr,textstatus,error){
17             //Code if fail
18          });
210. How to create Chatter post from Apex.
1//Adding a Text post
2FeedItem post = new FeedItem();
3post.ParentId = oId; //eg. Opportunity id, custom object id..
4post.Body = 'Enter post text here';
5insert post;
6 
7//Adding a Link post
8FeedItem post = new FeedItem();
9post.ParentId = oId; //eg. Opportunity id, custom object id..
10post.Body = 'Enter post text here';
11post.LinkUrl = 'http://www.someurl.com';
12insert post;
13 
14//Adding a Content post
15FeedItem post = new FeedItem();
16post.ParentId = oId; //eg. Opportunity id, custom object id..
17post.Body = 'Enter post text here';
18post.ContentData = base64EncodedFileData;
19post.ContentFileName = 'sample.pdf';
20insert post;
181. Lets consider your custom Object named “Training__c” has field “Trainer__c”. You have set some default value in that field. Will that default value apply to new record created by apex code ?
OR
How to make sure that record created from apex code should respect default value of fields ?
OR
Default value in field from Apex code.
Ans :
After API 20, it should automatically populate However there is known issue for same here, click here if it impacts you.
Workaround :
If Default value of field is not getting populated by Apex then we have to use “Dynamic Apex”.  Create instance of object from sObjectType like shown below:
1Training__c tr= (Training__c) Training__c.sObjectType.newSObject(nulltrue);
2 
3//Check if Value in field "Trainer__c" is default value
4System.assertEquals('Jitendra', tr.Trainer__c);
151. Give Sample Code Snippet of Apex that that will show that how Parent and Child record can be inserted in Single Statement ?
Ans : It can be done with help of External Id.
1Date dt = Date.today().addDays(7);
2Opportunity newOpportunity = new Opportunity(Name = 'shivasoft', StageName = 'Prospecting', CloseDate = dt);
3 
4/*
5Create the parent reference. Used only for foreign key reference  and doesn't contain any other fields. If we provide any other value it will give following error
6 
7System.DmlException: Insert failed. First exception on row 1; first error: INVALID_FIELD, More than 1 field provided in an external foreign key reference in entity: Account: []
8*/
9 
10Account accountReference = new Account(MyExtID__c = 'SHIVA1234567');
11newOpportunity.Account = accountReference;
12 
13//  Create the Account object to insert.  Same as above but has Name field.  Used for the insert.
14Account parentAccount = new Account(Name = 'Shiva', MyExtID__c = 'SHIVA1234567');
15 
16Database.SaveResult[]
17    results = Database.insert(new SObject[] {  parentAccount, newOpportunity });

152 . Which SOQL statement can be used to get all records even from recycle bin or Achieved Activities?
Ans : We will need “ALL Rows” clause of SOQL.
Sample :
1SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS

153. How can you lock record using SOQL so that it cannot be modified by other user.
Ans : we will need “FOR UPDATE” clause of SOQL.
Sample :
1Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];

154. If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, What will happen to later savepoint variables ?
Ans : if you generated savepoint SP1 first, savepoint SP2 after that, and then you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it.

155. What are few limitations (points to remember) of Savepoint or Transaction Control in Apex ?
Ans :
  • Each savepoint you set counts against the governor limit for DML statements.
  • Static variables are not reverted during a rollback. If you try to run the trigger again, the static variables retain the values from the first run.
  • Each rollback counts against the governor limit for DML statements. You will receive a Runtime error if you try to rollback the database additional times.
  • The ID on an sObject inserted after setting a savepoint is not cleared after a rollback.

156. What are few Considerations about Trigger ?
Ans :
  • upsert triggers fire both before and after insert or before and after update triggers as appropriate.
  • merge triggers fire both before and after delete triggers for the losing records and before update triggers for the winning record only.
  • Triggers that execute after a record has been undeleted only work with specific objects.
  • Field history is not recorded until the end of a trigger. If you query field history in a trigger, you will not see any history for the current transaction.
  • You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that is, when the method is defined with the @future keyword.
  • A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime error when the trigger is called in bulk from the Force.com API.
  • Merge trigger doesn’t fire there own trigger instead they fire delete and update of loosing and winning records respectively.

157. How to execute Apex from Custom button or Javascript ? Give Example.
Ans :
It is possible using Ajax toolkiit.
1global class myClass {
2    webService static Id makeContact (String lastName, Account a) {
3        Contact c = new Contact(LastName = lastName, AccountId = a.Id);
4        return c.id;
5    }
6}
we can execute above method from javascript like :
1{!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}
2{!REQUIRESCRIPT("/soap/ajax/33.0/apex.js")}
3var account = sforce.sObject("Account");
4var id = sforce.apex.execute("myClass" "makeContact",
5{lastName:"Smith", a:account});
To call a webService method with no parameters, use {} as the third parameter for sforce.apex.execute.
Also, you can use the following line to display a popup window with debugging information:
sforce.debug.trace=true;

158.  What is difference between public and global class in Apex ?
Ans :
  • Public class can be accessed within application or namespace. This is not exactly like public modifier in Java.
  • Global class visible everywhere , any application or namespace. WebService must be declared as Global and which can be accessed inside Javascript also. It is like public modifier in Java.

159. Explain Considerations for Static keyword in Apex.
Ans :
  • Apex classes cannot be static.
  • Static allowed only in outer class.
  • Static variables not transferred as a part of View State.
  • Static variables and static block runs in order in which they are written in class.
  • Static variables are static only in scope of request.

160. Explain few considerations for @Future annotation in Apex.
Ans :
  • Method must be static
  • Cannot return anything ( Only Void )
  • To test @future methods, you should use startTest and stopTest to make it synchromouse inside Test class.
  • Parameter to @future method can only be primitive or collection of primitive data type.
  • Cannot be used inside VF in Constructor, Set or Get methods.
  • @future method cannot call other @future method.

182. What is best practice to refer dynamic custom messages in Visualforce with multi-language support ?
Ans :
Using Custom Label or OutputField or InputField tag, Platform itself will take care of internationalization. However in some cases, Message needs to be dynamic at the same time it should also support muti-language. In Custom Label, we cannot save dynamic String.
Let’s assume we want to show message something like “DEVELOPERNAME is not authorized to access this page”.
Here, Developername should be dynamically changed in visualforce which supports multilanguage. For each developername, it is not feasible to create custom labels. So below workaround can be used :
Step 1 : Create a Custom Label with text “{0} is not authorized to access this page“. In every language, dynamic value should represented by {0}.
Step 2 : In Controller of Visualforce write something like this :
1String developerName = 'Some DeveloperName';
2String message = String.format(Label.DEVELOPERNA, new String[] { developerName });

183. How can you update Salesforce record using Apex, when you don’t know Object API name, but you know record Id ?
Ans :
Using Dynamic Apex we can achieve this :
1//Lets assume this is record Id
2Id recId = 'a0P9000000ESXcV';
3 
4Schema.SObjectType token = recId.getSObjectType();
5Sobject s = token.newSobject();
6s.put('Id',recId );
7s.put('Name''om');
8update s;

184. How to disable Header ribbon in Salesforce Organization where Community is enabled ?
Ans : In Profile “View Global Header” controlls visibility of B lack ribbon whioch is used to switch between community.

185. How many record can be displayed in repeater or PageBlockTable in Visualforce ?
Ans : current limit is 1000 records.

186. How to display more than 1000 records in repeater or PageBlockTable component of Visualforce ?
Ans : If circumstances permits, we can use readOnly attribute available at apex page level. Read more about making complete page readonly.

187. How we can check API limits already used in any organization by using REST or SOAP API ?
Ans :
SOAP API and REST API always returns header after making successful call to Salesforce.
Sample Responses:
SOAP :
1<soapenv:Header>
2    <LimitInfoHeader>
3        <limitInfo>
4            <current>45</current>
5            <limit>5000</limit>
6            <type>API REQUESTS</type>
7        </limitInfo>
8    </LimitInfoHeader>
9</soapenv:Header>
REST :
1Sforce-Limit-Info: api-usage=45/5000

188. Lets say you have written trigger on Opportynity and want to access field of Account. Can you use this Syntax – oppObj.Account.someField__c ?
Ans :
 There is common missunderstanding that what is allowed in Trigger Context. Above Syntax will work on any other places like Visualforce Controller. However in Trigger, Lookup field or related list is not available implicitly, we need to query it.

189. How we can control Chatter email settings while creating or updating users using Data Loader?
Ans : 
Using a dataloader update the user object’s field “DefaultGroupNotificationFrequency” with the options:
  • Email on each post
  • Daily digests
  • Weekly digests
  • Never

190. Once email is sent via Workflow, can it be tracked in Activity history related list ?
Ans : 
No. If you think this is nice to have and usefull for Auditing purpose,

No comments:

Post a Comment