Sunteți pe pagina 1din 12

Jitendra Questions

Q) Do governor limits apply to sandbox instances?


Ans : Governor limits do apply to all Salesforce instances (trial, developer, production or sandbox environments).
However code coverage and successful execution of test classes is only enforced when deploying to a production
environment.

Q) Is it possible to write the Apex code from user Interface?


You can add, edit, or delete Apex using the Salesforce.com user interface only in a Developer Edition organization,
a Salesforce.com Enterprise Edition trial organization, or sandboxorganization. In a Salesforce.com production
organization, you can only make changes to Apex by using the Metadata API 

Q) What are the types of email templates available in salesforce.com?


1. Text
2. HTML with Letter Head
3. Custom HTML
4. Visual force
Q) What will happen if the Account is deleted?
If the Account is deleted then Contact, Opportunity will also be deleted from Salesforce which are related to that
Account.
Q) How to create many to many relationships between object?
Creating many to many relationships in salesforce is little tricky. You cannot create this type of relationship
directly. Follow below steps to create this type of relationship.
Create both objects which should be interlinked.
Create one custom object (also called as junction object), which should have autonumber as unique identification
and create two master relationships for both objects, no need create tab for this object.
Now on both object, add this field as related list.
Check this article on blog to create many to many relationship in detail.
To study more in detail, please refer salesforce documents.

Q) How to delete the users data from Salesforce?


Ans : To delete the Users Data go to Setup | Administration Setup | Data Management |  Mass Delete Record,
from there select the objects like Account, Lead etc and in criteria select the users name and delete all records of
that user related to particular object.

Q) How to restrict the user to see any record, let’s say opportunity?
Ans : set up opportunity sharing to be private.  If both users are admins or have view all records on opportunity,
then that overrides private sharing.

Q) Where is the option of the report for the “Custom Object with related object” and what are the condition to
generate related reports?
If the parent object is the standard object provided by the salesforce like “Account”, “Contact” then the report will
be in there section with related custom object.
If both objects are the custom then the report will be in “Other Reports” Sections.
Following are the conditions to get the report of related objects:

 On both the objects, Reports option must be enable.


 Both object must be related either using Lookup or Master Detail type of field.
Q) Explain Test.setPage().
It is used to set the context to current page, normally used for testing the visual force controller.
Q) How to round the double to two decimal places in Apex?
Decimal d = 100/3;
Double ans = d.setScale(2) ;
Q) In Profile settings, what is difference between “Modify All Data” and “Modify All” ?
Ans:
Modify All Data : Create, edit, and delete all organization data, regardless of sharing settings.
Modify All : Give Read, Add, Delete permission to selected Object,  Create permission is not included in Modify All
permission.
Q) If I want record level access then what should I use from Salesforce security model?
Ans: Manual Sharing
Q) If I want Object level access then what should i use from Salesforce security model?
Ans: Profile
Q) In OWD (Organization wide sharing), can I change the setting “Grant Access Using Hierarchies” for Standard
Objects?
Ans: You cannot change it for Standard Objects However for Custom Objects its possible.
Q) What is Mandatory while creating User, Role or Profile?
Ans : Its Profile.
Q) In case of Master-Detail relationship, on Update of master record can we update the field of child record
using workflow rule?
Ans: No
Q) 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 “Criteria evaluation”.
Q) 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 the Parents setting.

Q) What is the need of “Custom Controller” in Visualforce as everything can be done by the combination of
Standard Controller + Extension class.
 Sharing setting is applied on standard object/extension by default; In case we don’t want to apply
sharing setting in our code then Custom controller is only option.
 It is possible that the functionality of page does not required any Standard object or may require
more than one standard object, then in that case Custom controller is required.

Q) In class declaration if we don’t write keyword “with sharing” then it runs in system mode then why keyword
“without sharing” is introduced in apex?
Lets take example, there is classA declared using “with sharing” and it calls classB method. classB is not declared
with any keyword then by default “with sharing” will be applied to that class because originating call is done
through classA. To avoid this we have to explicitly define classB with keyword “without sharing”.

Q) How many way we can invoke the Apex class?


1. Visualforce page
2. Trigger
3. Web Services
4. Email Services
Q) What is the difference between database.insert and insert ?
insert is the DML statement which is same as databse.insert. However, database.insert gives more flexibility like
rollback, default assignment rules etc. we can achieve the database.insert behavior in insert by using the method
setOptions(Database.DMLOptions)
Important Difference:
 If we use the DML statement (insert), then in bulk operation if error occurs, the execution will stop and
Apex code throws an error which can be handled in try catch block.
 If DML database methods (Database.insert) used, then if error occurs the remaining records will be
inserted / updated means partial DML operation will be done.
Q) What is the scope of static variable ?
When you declare a method or variable as static, it’s initialized only once when a class is loaded. Static variables
aren’t transmitted as part of the view state for a Visualforce page.
Static variables are only static within the scope of the request. They are not static across the server, or across the
entire organization.

Q) What happen if child have two master records and one is deleted?
Ans :Child record will be deleted.
Q) What is Scheduler class in Apex and explain how to use Crone statement to Schedule Apex class?
Ans:
The Apex class which is programed to run at pre defined interval.
Class must implement schedulable interface and it contains method named execute().
There are two ways to invoke schedular :

 Using UI
 Using System.schedule
The class which implements interface schedulable get the button texted with “Schedule”, when user clicks on
that button, new interface opens to schedule the classes which implements that interface.
To see what happened to scheduled job, go to “Monitoring | Scheduled jobs ”
Example of scheduling :
scheduledMerge m = new scheduledMerge();
String sch = '20 30 8 10 2 ?';
system.schedule('Merge Job', sch, m);
To see how to make crone job string – Refer this Online Crone Expression Generator tool .
Note : Salesforce only accepts integer in Seconds and Minutes. So, lets say if you want to run Apex job on every 10
minutes, crone statement will be ‘0 0/10 * 1/1 * ? *’ and salesforce will throw an error saying
“System.StringException: Seconds and minutes must be specified as integers“. That mean like Time based
Workflow, minimum interval to schedule job is 1 hour.

Apex Trigger Interview question:


1.What is trigger ?
Ans: Trigger is piece of code that is executes before and after a record is Inserted/Updated/Deleted
from the force.com database.

2.What are different types of triggers in SFDC?


1.Before Triggers-These triggers are fired before the data is saved into the database.
2.After Triggers-These triggers are fired after the data is saved into the database.

3.What are trigger context variables?


Trigger.isInsert: Returns true if the trigger was fired due to insert operation.
Trigger.isUpdate: Returns true if the trigger was fired due to update operation.
Trigger.isDelete: Returns true if the trigger was fired due to delete operation.
Trigger.isBefore: Returns true if the trigger was fired before record is saved.
Trigger.isAfter: Returns true if the trigger was fired after record is saved.
Trigger.New: Returns a list of new version of sObject records.
Trigger.Old: Returns a list of old version of sObject records.
Trigger.NewMap: Returns a map of new version of sObject records. (map is stored in the form of map )
Trigger.OldMap: Returns a map of old version of sObject records. (map is stored in the form of map)
Trigger.Size: Returns a integer (total number of records invoked due to trigger invocation for the both
old and new)
Trigger.isExecuting: Returns true if the current apex code is a trigger.

4.What is the difference between Trigger.New and Trigger.NewMap?


Ans:
Trigger.New is Returns a list of new version of sObject records but Trigger.NewMap is Returns a map of
new version of sObject records.

5.What is the difference between Trigger.New and Trigger.Old?


Ans:
Trigger.New is Returns a list of new version of sObject records and Trigger.Old is Returns a list of old
version of sObject records.

6.What is the difference between Trigger.New and Trigger.Old in update triggers?


Ans:

7.Can we call batch apex from the Trigger?


Ans: A batch apex can be called from a class as well as from trigger code.
In your Trigger code something like below :-
// BatchClass is the name of batchclass
BatchClass bh = new BatchClass();
Database.executeBacth(bh);

8.What are the problems you have encountered when calling batch apex from the trigger?
Ans: At a time only 5 apex batch jobs can be processed. Flex Queue does allow more than 5 concurrent
batch jobs but it simply lines up the remaining jobs and keep their status as "Holding". So, apparently
user feels that more than 5 jobs have been submitted but they all go in the "Holding" status.

Flex queue itself has a limit of holding up to 100 apex batch jobs only. Therefore, in a live org with
thousands of users working simultaneously, lining up apex batch jobs from a trigger will create issues. If
the apex flex queue reaches 100 jobs and at the same time a user tries to update something that is
further triggering an apex batch then s(he) will see the following error on screen:

"System.AsyncException: You've exceeded the limit of 100 jobs in the flex queue for org X. Wait for
some of your batch jobs to finish before adding more. To monitor and reorder jobs, use the Apex Flex
Queue page in Setup".

9.Can we call the callouts from trigger?


Ans: yes we can. It is same as usual class method calling from trigger. The only difference being the
method should always be asynchronous with @future
10.What are the problems you have encountered when calling apex the callouts in trigger?
Ans: Callout is a ASynchronous process where as Trigger is Dynamic / Synchrinous.
That means it is not directly possible to do a webservice callout from a triiger.
But using @Future annotation we can convert the Trigger into a Asynchrinous Class and we can use a
Callout method.
See the links below for some more information ,
You can invoke callouts from triggers by encapsulating the callouts in @future methods:
http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_cla
sses_annotation.htm?SearchType=Stem
Mentioned in the idea: https://success.salesforce.com/ideaview?id=087300000007LfiAAE
A related thread,

Callout from triggers are currently not supported.

11.What is the recursive trigger?


Ans: Recursion occurs in trigger if your trigger has a same DML statement and the same dml condition is
used in trigger firing condition on the same object(on which trigger has been written)

12.What is the bulkifying triggers?


Ans: By default every trigger is a bulk trigger which is used to process the multiple records at a time
as a batch. For each batch of 200 records.

13.What is the use of future methods in triggers?


Ans: Using @Future annotation we can convert the Trigger into a Asynchrinous Class and we can use a
Callout method.

14.What is the order of executing the trigger apex?


Ans:
1. Executes all before triggers.
2. Validation rules.
3. Executes all after triggers.
4. Executes assignment rules.
5. Executes auto-response rules.
6. Executes workflow rules.
7. If there are workflow field updates, updates the record again.
8. If the record was updated with workflow field updates, fires before and after triggers one more time.
Custom validation rules are not run again.
9. Executes escalation rules.
10. If the record contains a roll-up summary field or is part of a cross-object workflow, performs
calculations and updates the roll-up summary field in the parent record. Parent record goes through
save procedure.
11. If the parent record is updated, and a grand-parent record contains a roll-up summary field or is part
of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent
record. Grand-parent record goes through save procedure.
12. Executes Criteria Based Sharing evaluation.
13. Commits all DML operations to the database.
14. Executes post-commit logic. Ex: Sending email.

15.What is the trigger handler?


Ans:

16.How do we avoid recursive triggers?


Ans: Use a static variable in an Apex class to avoid an infinite loop. Static variables are local to the
context of a Web request.

17.How many triggers we can define on a object?


Ans: We can write more than one trigger But it is not recommended .Best practice is One trigger On One
object. 

18.Can we define triggers with same event on single object?


Ans:

19.Tell me more scenarios where you have written triggers?


Ans:

20.What is the best scenario that you have developed on triggers?


Ans:

21.How many time workflow filed update will be called in triggers?


Ans:

Q) How to restrict any Trigger to fire only once OR how we can avoid repeated or multiple execution of Trigger?
Ans:
Triggers can fire twice, once before workflows and once after workflows, this is documented at
http://www.salesforce.com/us/developer/docs/apexcode/ Content/ apex_triggers_order_of_execution.htm:
“The before and after triggers fire one more time only if something needs to be updated. If the fields have already
been set to a value, the triggers are not fired again.”
Workaround:
Add a static Boolean variable to a class and check its value within the affected triggers.
public class HelperClass {
public static boolean firstRun = true;
}
trigger affectedTrigger on Account (before delete, after delete, after undelete) {
if(Trigger.isBefore){
if(Trigger.isDelete){
if(HelperClass.firstRun){
Trigger.old[0].addError('Before Account Delete Error');
HelperClass.firstRun=false;
}
}
}
}
Q) If one object in Salesforce have 2 triggers which runs “before insert”. Is there any way to control the
sequence of execution of these triggers?
Ans : Salesforce.com has documented that trigger sequence cannot be predefined. As a best practice create one
trigger per object and use comment blocks to separate different logic blocks. By having all logic in one trigger you
may also be able to optimize on your SOQL queries.

1. How would you invoke the apex class through the process Builder?
 In Process builder select immediate action
 Select Action type as APEX and Apex Class
Note: Apex class method should me @InvokableMethod to call in Process builder.
https://blog.webnersolutions.com/salesforce-call-apex-class-from-process-builder

2. How you will pass parameters (Ex: id of record) for an apex class through process builder?
Apex variable selection ->You can select formula, Global constant, reference,
and id

3. How to avoid the recursive triggers?


Avoid recursive trigger in salesforce using static variable
Recursion occurs when same code is executed again and again. It can lead to infinite loop and which can result
to governor limit sometime. Sometime it can also result in unexpected output.
It is very common to have recursion in trigger which can result to unexpected output or some error. So we
should write code in such a way that it does not result to recursion. But sometime we are left with no choice.
For example, we may come across a situation where in a trigger we update a field which in result invoke a
workflow. Workflow contains one field update on same object. So trigger will be executed two times. It can
lead us to unexpected output.
Another example is our trigger fires on after update and it updates some related object and there is one more
trigger on related object which updates child object. So it can result too infinite loop.
To avoid these kind of situation we can use public class static variable.
In RecursiveTriggerHandler class, we have a static variable which is set to true by default.
publicclassRecursiveTriggerHandler{
     publicstaticBoolean isFirstTime = true;
}
In following trigger, we are checking if static variable is true only then trigger runs. Also we are setting static
variable to false when trigger runs for first time. So if trigger will try to run second time in same request then it
will not run.
trigger SampleTrigger on Contact (after update){
 
    Set<String>accIdSet = newSet<String>();
     
    if(RecursiveTriggerHandler.isFirstTime){
        RecursiveTriggerHandler.isFirstTime = false;
         
        for(Contact conObj : Trigger.New){
            if(conObj.name != 'SFDC'){
                accIdSet.add(conObj.accountId);
            }
        }
         
        // Use accIdSet in some way
    }
}
4. What is the purpose of Wrapper Class and its usage?
A wrapper or container class is a class, a data structure, or an abstract data type which contains different objects or
collection of objects as its members.
A wrapper class is a custom object defined by programmer wherein he defines the wrapper class properties.
Consider a custom object in salesforce, what do you have in it? fields right? different fields of different data types.
Similarly, wrapper class is a custom class which has different data types or properties as per requirement. We can
wrap different objects types or any other types in a wrapper class.
In the Visualforce most, important use case is to display a table of records with a check box and then process only
the records that are selected.
In the example below, we are displaying list of accounts with checkbox. End user can select account and then click
on Show Selected accounts button. Then selected account will be displayed in table.

<apex:page controller="AccountSelectClassController" sidebar="false">


<script type="text/javascript">
function selectAllCheckboxes(obj,receivedInputID){
var inputCheckBox = document.getElementsByTagName("input");
for(var i=0; i<inputCheckBox.length; i++){
if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
inputCheckBox[i].checked = obj.checked;
}
}
}
</script>
<apex:form>
<apex:pageBlock>
<apex:pageBlockButtons>
<apex:commandButton value="Show Selected Accounts" action="{!processSelected}" rerender="table2"/>
</apex:pageBlockButtons>
<apex:pageblockSection title="All Accounts" collapsible="false" columns="2">
<apex:pageBlockTable value="{!wrapAccountList}" var="accWrap" id="table" title="All Accounts">
<apex:column>
<apex:facet name="header">
<apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
</apex:facet>
<apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
</apex:column>
<apex:column value="{!accWrap.acc.Name}" />
<apex:column value="{!accWrap.acc.BillingState}" />
<apex:column value="{!accWrap.acc.Phone}" />
</apex:pageBlockTable>
<apex:pageBlockTable value="{!selectedAccounts}" var="c" id="table2" title="Selected Accounts">
<apex:column value="{!c.Name}" headerValue="Account Name"/>
<apex:column value="{!c.BillingState}" headerValue="Billing State"/>
<apex:column value="{!c.Phone}" headerValue="Phone"/>
</apex:pageBlockTable>
</apex:pageblockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Custom Controller:
public class AccountSelectClassController{
//Our collection of the class/wrapper objects wrapAccount
public List<wrapAccount>wrapAccountList {get; set;}
public List<Account>selectedAccounts{get;set;}
public AccountSelectClassController(){
if(wrapAccountList == null) {
wrapAccountList = new List<wrapAccount>();
for(Account a: [select Id, Name,BillingState, Website, Phone from Account limit 10]) {
// As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
wrapAccountList.add(new wrapAccount(a));
}
}
}
public void processSelected() {
selectedAccounts = new List<Account>();
for(wrapAccountwrapAccountObj : wrapAccountList) {
if(wrapAccountObj.selected == true) {
selectedAccounts.add(wrapAccountObj.acc);
}
}
}
// This is our wrapper/container class. In this example a wrapper class contains both the standard salesforce
object Account and a Boolean value
public class wrapAccount {
public Account acc {get; set;}
public Boolean selected {get; set;}
public wrapAccount(Account a) {
acc = a;
selected = false;
}
}
}

1. What is the use of with sharing and without sharing keyword?

https://www.tutorialkart.com/apex_soql/apex-access-modifiers-with-sharing-without-sharing/

With Sharing:
If you declare a class as a with sharing, sharing rules given to the current user will be taken to the consideration
and the user can access or perform the operations based on the permissions given to him on object and fields
(Field level security and sharing rules)

Without Sharing:
If you declare a class as a without sharing, then this Apex class runs in system mode which means Apex code has
access to all the objects and field irrespective of current users sharing rules, field level security and object
permissions.
 If the class is not declared as without sharing or with sharing then the class is by default taken as
with sharing.
 Both inner and outer class can be declared as with sharing.
 If the inner class declared as with sharing and top-level class is declared as without sharing, then
by default entire context will run with sharing context.
 If a class in not declared as with/without sharing and if this class is called by another class in
which sharing rules is enforced then both the classes run with sharing.
 Outer class is declared as with sharing and inner class is declared as without sharing, then the
inner class runs in without sharing context.

2. Is it possible to deploy a trigger without it’s test class if org has code coverage of >75%, if not then what
is the minimum code coverage to deploy?

 At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete
successfully. Note the following:
 When deploying to a production organization, every unit test in your organization namespace is executed.
 Calls to System.debug are not counted as part of Apex code coverage.
 Test methods and test classes are not counted as part of Apex code coverage.
 While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of
code that is covered. Instead, you should make sure that every use case of your application is covered,
including positive and negative cases, as well as bulk and single records. This should lead to 75% or more
of your code being covered by unit tests.
 Every trigger must have some test coverage.
 All classes and triggers must compile successfully.

3. What is the use of global keyword?

Global Keyword :-

This means the method or variable can be used by any Apex code that has access to the class, not just the Apex
code in the same application. This access modifier should be used for any method that needs to be referenced
outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable as
global, you must also declare the class that contains it as global.

4. How to throw an error from trigger?


Using addError() method, can through error from trigger.

Ex: trinner.new.addError(‘Error’);
Contact.LastName.addError(‘Error’);

5. With Apex triggers how would they usually execute it as? Will they take users sharing rules into
consideration?  Do they run Apex triggers in user context?
System mode -
System mode is nothing but running apex code by ignoring user's permissions. For example, logged in user does
not have create permission but he/she is able to create a record.
In system mode, Apex code has access to all objects and fields— object permissions, field-level security, sharing
rules aren't applied for the current user. This is to ensure that code won’t fail to run because of hidden fields or
objects for a user.
In Salesforce, all apex code run in system mode. It ignores user's permissions. Only exception is anonymous blocks
like developer console and standard controllers. Even runAs() method doesn't enforce user permissions or field-
level permissions, it only enforces record sharing.

User mode -
User mode is nothing but running apex code by respecting user's permissions and sharing of records. For example,
logged in user does not have create permission and so he/she is not able to create a record.
In Salesforce, only standard controllers and anonymous blocks like developer console run in user mode.

6. From Salesforce standpoint, is it best to use out of box /write Apex code, what would you do when you
are given a requirement? Walk me through your thought process?

1. First, I check for existing salesforce functionality for my requirement


2. Or Try to modify salesforce functionality
3. If not available then customize functionality as per requirement using Apex code

7. In a project, for custom functionality you were required to add functionality to an object, especially
write Apex trigger code and let’s say you have Trigger on custom object A, what would you do in that scenario?

8. If you look at custom object and there are already 5 triggers …would you write new trigger or would
you change the existing trigger?

All the triggers will run, but the order of execution is not predictable also we
can't prioritize one.

The order of execution isn’t guaranteed when having multiple triggers for the
same object due to the same event. For example, if you have two before insert
triggers for Case, and a new Case record is inserted that fires the two
triggers, the order in which these triggers fire isn’t guaranteed.

Ref: https://developer.salesforce.com/docs/atlas.en-
us.apexcode.meta/apexcode/apex_triggers_order_of_execution.htm

Multiple Trigger Approach:


This approach is suitable only when the order of execution of the multiple
triggers is not a concern. You will have to assess if your organization or the
functionalities in hand should be executed in any specific order. If that is a
non-issue, then it is an option to consider if it fits your needs.

1) Multiple triggers would mean lines of code in each trigger is significantly


less.
2) You can name the trigger depending on the functionality implemented.
3) Salesforce provides you with the ability to deactivate a trigger if need be
and if a specific functionality is no longer needed, you can deactivate the one
trigger eliminating the need to touch code and subsequent production
deployment.
4) Searching of functionality becomes simple if a good naming convention is
used for the various triggers.

Best Practice: Streamline Multiple Triggers on same Object:


https://developer.salesforce.com/page/Best_Practice:_Streamline_Multiple_Trig
gers_on_same_Object

Hope this help,

If our suggestion seems relevant then please mark the most appropriate
answer as "Best Answer" right under the comment. This will help other
community members if they would have a similar issue in the future, also help
us to keep this community clean

9. What is After Undelete event in triggers?

The after undelete trigger event only works with recovered records—that is, records that were deleted and then
recovered from the Recycle Bin through the undelete DML statement. ... The after undelete trigger events only run
on top-level objects.
For example, if you delete an Account, an Opportunity may also be deleted.

S-ar putea să vă placă și