Top 47 Apex Interview Questions
Q1. How To Restrict Any Trigger To Fire Only Once?
Triggers can fire twice, once earlier than workflows and as soon as after workflows.
“The earlier than and after triggers hearth one more time handiest if some thing needs to be updated, If the fields have already been set to a value, the triggers are not fired once more.”
Workaround:
public magnificence HelperClass
public static boolean firstRun = actual;
trigger affectedTrigger on Account (before delete, after delete, after undelete)
if(Trigger.IsBefore)
if(Trigger.IsDelete)
if(HelperClass.FirstRun)
Trigger.Antique[0].AddError('Before Account Delete Error');
HelperClass.FirstRun=false;
Q2. What Is S-manage?
S-Controls are the most important salesforce.Com widgets that are completely based totally on Javascript. These are hosted by means of salesforce however performed at client facet. S-Controls are outdated by using Visualforce now.
Q3. What Are Custom Settings?
Custom settings are similar to custom objects and enable application builders to create custom units of data, as well as create and accomplice custom statistics for an enterprise, profile, or unique user. All custom settings information is uncovered within the software cache, which allows efficient access with out the cost of repeated queries to the database. This statistics can then be utilized by formula fields, validation guidelines, Apex, and the SOAP API.
There are two forms of custom settings:
List Custom Settings
A type of custom placing that provides a reusable set of static data that may be accessed throughout your corporation. If you operate a selected set of records frequently inside your application, putting that information in a list custom putting streamlines get entry to to it. Data in list settings does now not vary with profile or consumer, however is to be had organisation-wide. Because the statistics is cached, get entry to is low-fee and green: you don't have to use SOQL queries that rely in opposition to your governor limits.
Hierarchy Custom Settings
A form of custom putting that makes use of a integrated hierarchical good judgment that helps you to “customize” settings for precise profiles or customers. The hierarchy logic assessments the agency, profile, and user settings for the present day consumer and returns the most particular, or “lowest,” value. In the hierarchy, settings for an organisation are overridden via profile settings, which, in turn, are overridden by way of user settings.
Q4. Explain Difference In Count() And Count(fieldname) In Soql.?
COUNT()
COUNT() need to be the handiest element within the SELECT listing.
You can use COUNT() with a LIMIT clause.
You can’t use COUNT() with an ORDER BY clause. Use COUNT(fieldName) as a substitute.
You can’t use COUNT() with a GROUP BY clause for API version 19.0 and later. Use COUNT(fieldName) as a substitute.
COUNT(fieldName)
You can use COUNT(fieldName) with an ORDER BY clause.
You can use COUNT(fieldName) with a GROUP BY clause for API version 19.Zero and later.
Q5. What Is The Scope Of Static Variable?
When you claim a method or variable as static, it’s initialized handiest once when a class is loaded. Static variables aren’t trmitted as a part of the view kingdom for a Visualforce web page.
Static variables are simplest static inside the scope of the request. They aren't static throughout the server, or across the whole company.
Q6. In Which Sequence Trigger And Automation Rules Run In Salesforce.Com?
The following is the order salesforce good judgment is applied to a record.
@ Old record loaded from database (or initialized for brand new inserts)
@ New report values overwrite old values
@ System Validation Rules
@ All Apex “earlier than” triggers (EE / UE handiest)
@ Custom Validation Rules
@ Record saved to database (but now not dedicated)
@ Record reloaded from database
@ All Apex “after” triggers (EE / UE handiest)
@ Assignment rules
@ Auto-response guidelines
@ Workflow regulations
@ Escalation rules
@ Parent Rollup Summary Formula fee up to date (if present)
@ Database dedicate
@ Post-dedicate logic (sending e mail)
Additional notes: There is no manner to govern the order of execution within each institution above.
Q7. How Validation Rules Executed? Is It Page Layout / Visualforce Dependent?
The validation policies run on the records version degree, so they are not laid low with the UI. Any file this is stored in Salesforce will run thru the validation regulations.
Q8. What Is Visualforce View State? And What Are Best Practices To Reduce The View State Size?
Visualforce pages that include a shape factor also include an encrypted, hidden form subject that encapsulates the view state of the web page. This view nation is robotically created, and as its name suggests, it holds the nation of the page – country that consists of the additives, subject values and controller nation.
Best Practices to lessen the view nation length:
Minimize variety of shape on a page. Use apex:actionRegion in preference to the use of 2 or extra paperwork.
Refine your SOQL to most effective retrieve the facts wished through the page.
All public and personal statistics members found in Standard, Custom and Controller extensions are stored.
Mark any Apex variables that are not important to the view country as Trient. (The trient variables aren't handed to view nation and consequently no longer saved in View State)
Create wizards with as few pages as viable
Use outputLink components in place of commandLink or commandButton components where possible as they don’t need to be nested in a form.
Q9. How To Read The Parameter Value From The Url In Apex?
Consider that the parameter name is “RecordType”.
String recordType = Apexpages.CurrentPage().GetParameters().Get('RecordType');
Q10. Explain System.Runas()?
Generally, all Apex code runs in device mode, and the permissions and record sharing of the modern-day person aren't taken under consideration. The gadget technique, System.RunAs(), lets you write test strategies that change consumer contexts to either an present person or a brand new user. All of that user’s document sharing is then enforced. You can most effective use runAs in a test approach. The unique system context is commenced once more in any case runAs() test strategies whole.
Example :
System.RunAs(u)
// The following code runs as consumer 'u'
System.Debug('Current User: ' + UserInfo.GetUserName());
System.Debug('Current Profile: ' + UserInfo.GetProfileId());
// Run a few code that checks document sharing
Q11. What Is Apex?
It is the in-house era of salesforce.Com which is just like Java programming with item orientated concepts and to put in writing our very own custom logic.
• Apex is a procedural scripting language in discrete and finished by way of the Force.Com platform.
• It runs natively at the Salesforce servers, making it extra powerful and quicker than non-server code, inclusive of JavaScript/AJAX.
• It uses syntax that looks as if Java
• Apex can written in triggers that act like database saved approaches.
• Apex permits builders to attach enterprise good judgment to the record store procedure.
• It has built-in support for unit check advent and execution.
Apex affords built-in help for commonplace Force.Com platform idioms, which include:
• Data manipulation language (DML) calls, such as INSERT, UPDATE, and DELETE, that include built-in DmlException coping with
• Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that go back lists of sObject statistics
- Looping that lets in for bulk processing of multiple records at a time
- Locking syntax that stops document update conflicts
- Custom public Force.Com API calls that can be constructed from saved Apex methods
- Warnings and mistakes issued while a person attempts to edit or delete a custom item or field that is referenced by Apex
Note: Apex is included in Unlimited Edition, Developer Edition, Enterprise Edition, and Database.Com
Apex vs. Java: Commonalities
• Both have instructions, inheritance, polymorphism, and other commonplace OOP capabilities.
• Both have the same name variable, expression, and looping syntax.
• Both have the same block and conditional declaration syntax.
• Both use the equal item, array, and remark notation.
• Both are compiled, strongly-typed, and tractional.
Apex vs. Java: Differences
• Apex runs in a multi-tenant environment and is very controlled in its invocation and governor limits.
• To keep away from confusion with case-insensitive SOQL queries, Apex is also case-insensitive.
• Apex is on-call for and is compiled and executed in cloud.
• Apex is not a fashionable reason programming language, however is instead a proprietary language used for precise enterprise common sense features.
• Apex requires unit checking out for development right into a manufacturing environment.
Q12. What Are Merge Fields? Explain With Example?
Merge fields are fields that we can installed Email templates, mail merge templates, custom hyperlink or method fields to include values from a document.
Example: !CustomObject.FieldName__c
Q13. Onchange Event Does Not Work With <apex:actionsupport> In Ie
If we add the Header on Visualforce web page then it creates masses of problem in IE@I suppose there are few java-script library loaded by way of Header of Salesforce which makes IE9 compatible. So the satisfactory answer is to allow the Header through using “showHeader=true” in Apex web page.
Q14. Where To Write Visualforce Code?
You can write the code basically in 3 approaches.
@ setup->App Setup->Develop->Pages and create new Visulaforce page.
@ Setup -> My Personal Information -> Personal Information -> Edit check the checkbox development mode. When you run the page like this, https://ap1.Salesforce.Com/apex/MyTestPage.You may locate the Page editor at the lowest of the web page. You can write you page as well as the controller class associated with it, there itself.
@ Using Eclipse IDE you can create the Visulaforce web page and write the code.
Q15. If Ie9 Is Not Working With Your Custom Visualforce Page Then How To Tell Your Visualforce Code To Run In Ie8 Compatibility Mode?
Add following metatag to pages:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
Q16. How To Get The List Of All Available Sobject In Salesforce Database Using Apex (dynamic Apex)?
Map<String, Schema.SObjectType> m = Schema.GetGlobalDescribe();
Q17. How To Create Many To Many Relationships Between Object?
Creating Many to Many courting in salesforce is little elaborate. You can't create this form of relationship at once. Follow underneath steps to create this form of dating.
Create each gadgets which should be interlinked.
Create one custom item (also called as junction object), which need to have automobile number as precise identification and create grasp relationships for each gadgets, no want create tab for this object.
Now on both objects, upload this subject as related list.
Q18. What Are The Types Of Controller In Visualforce?
There are basically two sorts of Controller in Visual force page.
@ Standard Controller
@ Custom Controller
Q19. What Is The Controller Extension?
Any apex magnificence having a public constructor with Custom Controller or Standard Controller item as a unmarried argument is called controller extension.
Q20. Will Visual Force Still Supports The Merge Fields Usage Like S-manage?
Just like S-Controls, Visualforce Pages assist embedded merge fields, just like the !$User.FirstName utilized in the instance.
Q21. How To Get All The Fields Of Sobject Using Dynamic Apex?
Map<String, Schema.SObjectType> m = Schema.GetGlobalDescribe() ;
Schema.SObjectType s = m.Get('API_Name_Of_SObject') ;
Schema.DescribeSObjectResult r = s.GetDescribe() ;
Map<String,Schema.SObjectField> fields = r.Fields.GetMap();
Q22. How To Get All The Required Fields Of Sobject Dynamically?
There is no direct belongings available in Apex dynamic API to represent the specified field. However there's any other manner to understand about it.
If any fields have under three properties then it's miles obligatory subject.
If it is Creatable
If it isn't nillable and
If it does no longer have any default cost
Map<String, Schema.SObjectType> m = Schema.GetGlobalDescribe() ;
Schema.SObjectType s = m.Get(so.ApiName) ;
Schema.DescribeSObjectResult r = s.GetDescribe() ;
Map<String,Schema.SObjectField> fields = r.Fields.GetMap() ;
for(String f : fields.Keyset())
Schema.DescribeFieldResult desribeResult = fields.Get(f).GetDescribe();
if( desribeResult.IsCreateable() && !DesribeResult.IsNillable() && !DesribeResult.IsDefaultedOnCreate() )
//This is mandatory / required subject
Q23. What Is Difference In Isnull And Isblank?
ISNULL:
Determines if an expression is null (clean) and returns TRUE if it is. If it carries a value, this characteristic returns FALSE.
Text fields are never null, so using this function with a text subject constantly returns false. For example, the system subject IF(ISNULL(new__c) 1, zero) is continually zero irrespective of the price inside the New area. For textual content fields, use the ISBLANK feature as a substitute.
Multi-pick out picklist fields are by no means null in s-controls, buttons, and e mail templates, so the use of this characteristic with a multi-pick out picklist subject in those contexts constantly returns fake.
Empty date and date/time fields constantly go back genuine while referenced in ISNULL capabilities.
Choose Treat clean fields as blanks in your components when referencing a number, percent, or foreign money field in an ISNULL feature. Choosing Treat clean fields as zeroes offers blank fields the fee of zero so none of them can be null.
Merge fields may be dealt with as blanks, which could have an effect on the results of components like s-controls because they are able to call this characteristic.
When the use of a validation rule to ensure that quite a number subject includes a specific value, use the ISNULL feature to include fields that do not include any cost. For example, to validate that a custom discipline consists of a price of ’1,’ use the subsequent validation rule to show an errors if the sector is blank or some other variety: OR(ISNULL(field__c), field__c<>1)
ISBLANK:
Determines if an expression has a fee and returns TRUE if it does not. If it carries a value, this feature returns FALSE.
Use ISBLANK in preference to ISNULL in new formulas. ISBLANK has the same functionality as ISNULL, but also supports textual content fields. Salesforce.Com will continue to assist ISNULL, so you do not need to change any current formulation.
A discipline isn't empty if it carries a person, clean area, or 0. For example, a subject that carries a space inserted with the spacebar isn't empty.
Use the BLANKVALUE function to return a specific string if the field does no longer have a cost; use the ISBLANK function if you simplest want to test if the field has a fee.
If you operate this characteristic with a numeric discipline, the characteristic simplest returns TRUE if the sphere has no value and isn't configured to deal with blank fields as zeroes.
Q24. How To Display The Formatted Number / Date In Visual Force? Which Component Should Be Used?
Use component “<apex:outputText>”.
Example : Format the variety into currency.
<apex:outputtext value="0, number, 000,000.00">
<apex:param value="!ValFromController" />
</apex:outputtext>
OR
<apex:outputtext value="0, number, ###,###.00">
<apex:param value="!ValFromController" />
</apex:outputtext>
Q25. You Want To Display The Encrypted Field On Visualforce And You Are Using Component Apex:outputtext. Will It Work For Encrypted Fields?
Encrypted custom fields which might be embedded in the <apex:outputText> issue show in clear text. The <apex:outputText> factor doesn’t recognize the View Encrypted Data permission for users. To save you showing touchy data to unauthorized customers, use the <apex:outputField> tag instead.
Q26. What Is Difference In Render, Rerender And Renderas Attributes Of Visualforce?
Render – It works like “display” belongings of CSS. Used to reveal or hide detail.
Rerender – After Ajax which component should be refreshed – to be had on commandlink, commandbutton, actionsupport and many others.
Renderas – render page as pdf, doc and excel.
Q27. How To Schedule A Class In Apex?
To invoke Apex classes to run at precise instances, first put into effect the Schedulable interface for the class, then specify the time table using either the Schedule Apex web page inside the Salesforce consumer interface, or the System.Time table technique.
After you enforce a category with the Schedulable interface, use the System.Schedule technique to execute it. The scheduler runs as machine: all instructions are finished, whether the consumer has permission to execute the magnificence or no longer.
The System.Schedule technique takes three arguments: a name for the task, an expression used to symbolize the time and date the job is scheduled to run, and the name of the elegance.
Salesforce best adds the technique to the queue at the scheduled time. Actual execution can be behind schedule primarily based on provider availability. The System.Schedule technique makes use of the person's time zone for the basis of all schedules. You can simplest have 25 instructions scheduled at one time.
Example Code:
String CRON_EXP = '0 zero * * * ?';
clsScheduledHourly sch = new clsScheduledHourly();
system.Schedule('Hourly Sync', CRON_EXP, sch);
Q28. What Is The Difference Between Database.Insert And Insert?
Insert is the DML declaration that is equal as databse.Insert.
However, database.Insert offers extra flexibility like rollback, default assignment rules etc. We are able to reap the database.Insert behavior in insert by using the use of the technique setOptions(Database.DMLOptions)
Important Difference:
If we use the DML announcement (insert), then in bulk operation if error takes place, the execution will stop and Apex code throws an errors which can be dealt with in strive seize block.
If DML database methods (Database.Insert) used, then if mistakes takes place the closing data can be inserted / updated me partial DML operation could be performed.
Q29. What Happens If Child Have Two Master Records And One Is Deleted?
Child record might be deleted.
Q30. Explain Test.Setpage().?
It is used to set the context to modern-day page, normally used for trying out the visual force controller.
Q31. How Many Controllers Can Be Used On Single Vf Page?
Only one controller can be used salesforce. Other than them, Controller extension can be used.
There may be more than one Controller extension.
Example:
<apex:page standardController="Account"
extensions="ExtOne,ExtTwo" showHeader="false">
<apex:outputText value="!Foo" />
</apex:page>
if ExtOne and ExtTwo, both have the technique getFoo() then the approach of ExtOne might be carried out.
A controller extension is any Apex elegance that incorporates a constructor that takes a single argument of typeApexPages.StandardController or CustomControllerName, wherein CustomControllerName is the call of a custom controller that you need to increase.
Q32. How To Get The Picklist Value In Apex Class?
Using Dynamic apex, we can attain this. On object of kind pickilist, call getDescribe(). Then call the getPicklistValues() technique. Iterate over end result and create a listing. Bind it to <apex:selectOptions>.
Code Example:
Let’s say we have a custom object called OfficeLocation__c. This item consists of a picklist discipline Country__c.
The first thing we need to do, within our controller is use the getDescribe() technique to gain statistics on
the Country__c discipline:
Schema.DescribeFieldResult fieldResult = OfficeLocation__c.Country__c.GetDEscribe();
We recognise that Country__c is a picklist, so we need to retrieve the picklist values:
List<Schema.PicklistEntry> ple = fieldResult.GerPicklistValues();
The handiest issue left for us to do is map the picklist values into an <apex:selectOptions> tag can use for display. Here is the whole technique from our controller to do this:
public List<SelectOption> getCountries()
List<SelectOption> alternatives = new List<SelectOption>();
Schema.DescribeFieldResult fieldResult =
OfficeLocation__c.Country__c.GetDescribe();
List<Schema.PicklistEntry> ple = fieldResult.GetPicklistValues();
for( Schema.PicklistEntry f : ple)
options.Upload(new SelectOption(f.GetLabel(), f.GetValue()));
go back options;
With our controller common sense all entire, we are able to name the getCountries() technique from our Visualforce page, and populate the <apex:selectList> tag:
<apex:selectList id="countries" value="!Office_Location__c.Country__c"
size="1" required="true">
<apex:selectOptions value="!Countries"/>
</apex:selectList>
Q33. What Are Global Variables Explain With Examples?
Global variables are the variables used to reference the overall facts about the modern-day person or your business enterprise on a web page.
Example:
Global variables must be referenced the use of Visualforce expression syntax to be evaluated, as an example, !$User.Name.
List of available global variables are as underneath:
@ $Action
@ $Api
@ $Component
@ $ComponentLabel
@ $CurrentPage
@ $Label
@ $Label.Site
@ $ObjectType
@ $Organization
@ $Page
@ $Profile
@ $Resource
@ $SControl
@ $Setup
@ $Site
@ $User
@ $UserRole
@ $System.OriginDateTime
@ $ User.UITheme and $User.UIThemeDisplayed
Q34. In How Many Ways We Can Invoke The Apex Class?
@ Visualforce page
@ Trigger
@ Web Services
@ Email Services
Q35. What Is Property In Apex? Explain With Advantages.?
Apex in particular includes the syntax from the widely recognized programming language Java. As a exercise of encapsulation in java we claim any variable as personal and then create the setters and getters for that variable.
Non-public String call;
public void setName(String n)
call = n;
public String getName()
return name;
However, the Apex delivered the brand new concept of assets from language C# as shown beneath:
public String call get; set;
As we are able to see how easy the code is and as opposed to using almost 8 to eleven lines all accomplished in 1 line simplest. It may be very beneficial whilst plenty of member is declared in Apex elegance. It has another benefit in “variety of strains of code” restriction by way of salesforce with a view to appreciably reduced.
Q36. What Are Different Apis In Salesforce.Com?
REST API:
REST API presents a powerful, handy, and easy REST-primarily based Web services interface for interacting with Salesforce. Its advantages consist of ease of integration and development, and it’s an notable desire of technology to be used with cellular packages and Web initiatives. However, if you have a huge variety of information to process, you may want to use Bulk API, which is based totally on REST concepts and optimized for large units of statistics.
SOAP API:
SOAP API offers a powerful, handy, and simple SOAP-based Web services interface for interacting with Salesforce.You can use SOAP API to create, retrieve, update, or delete facts. You can also use SOAP API to carry out searches and lots more. Use SOAP API in any language that supports Web services.
For example, you may use SOAP API to integrate Salesforce with your business enterprise’s ERP and finance systems, supply real-time sales and assist facts to agency portals, and populate crucial business structures with patron information.
Chatter API:
Chatter API is a REST API that offers programmatic access to Chatter feeds and social facts consisting of customers, organizations, followers, and documents. It's used by builders who need to combine Chatter into an expansion of packages together with cell programs, intranet websites, and third-party Web applications. Chatter API is much like APIs supplied via other agencies with feeds, such as Facebook and Twitter. Its advantages include ease of integration and improvement.
Bulk API:
Bulk API is primarily based on REST concepts and is optimized for loading or deleting large units of data. You can use it to query, insert, replace, upsert, or delete a huge number of statistics asynchronously via submitting batches which can be processed inside the heritage by Salesforce.
SOAP API, in comparison, is optimized for actual-time customer packages that update small numbers of statistics at a time. Although SOAP API also can be used for processing huge numbers of facts, whilst the facts units contain loads of hundreds of facts, it turns into much less sensible. Bulk API is designed to make it easy to manner statistics from a few thousand to tens of millions of statistics.
The simplest manner to use Bulk API is to permit it for processing data in Data Loader the use of CSV files. This avoids the need to write down your personal purchaser utility.
Metadata API:
Use Metadata API to retrieve, set up, create, replace, or delete customizations on your corporation. The most common use is emigrate changes from a sandbox or trying out company on your production surroundings. Metadata API is intended for handling customizations and for building tools that can manipulate the metadata version, no longer the statistics itself.
The easiest manner to get admission to the capability in Metadata API is to use the Force.Com IDE or Force.Com Migration Tool. These gear are built on pinnacle of Metadata API and use the same old Eclipse and Ant gear respectively to simplify the project of operating with Metadata API. Built at the Eclipse platform, the Force.Com IDE presents a comfortable surroundings for programmers familiar with incorporated development environments, permitting you to code, compile, check, and install all from in the IDE itself. The Force.Com Migration Tool is good if you need to use a script or a command-line software for transferring metadata between a nearby listing and a Salesforce corporation.
Streaming API:
Use Streaming API to acquire notifications for modifications to information that in shape a SOQL question that you define.
Streaming API is beneficial when you want notifications to be pushed from the server to the customer. Consider Streaming API for applications that ballot frequently. Applications that have constant polling action in opposition to the Salesforce infrastructure, ingesting pointless API call and processing time, might benefit from this API which reduces the range of requests that return no facts. Streaming API is also ideal for packages that require preferred notification of records modifications. This enables you to lessen the range of API calls and improve performance.
Apex REST API:
Use Apex REST API when you need to expose your Apex instructions and strategies so that outside programs can access your code thru REST structure. Apex REST API helps both OAuth 2.Zero and Session ID for authorization.
Apex SOAP API:
Use Apex SOAP API while you want to expose your Apex techniques as SOAP Web service APIs so that external applications can get admission to your code through SOAP. Apex SOAP API helps each OAuth 2.Zero and Session ID for authorization.
Q37. Explain The Apex Data Manipulation Language (dml) Operations?
Use records manipulation language (DML) operations to insert, update, delete, and restore facts in a database.
You can execute DML operations the usage of two distinctive forms:
Apex DML statements, inclusive of:
insertSObject[]
Apex DML database methods, along with:
Database.SaveResult[] end result = Database.Insert(SObject[])
While maximum DML operations are to be had in either shape, some exist simplest in a single form or the alternative.
The distinct DML operation forms permit different kinds of exception processing:
Use DML statements in case you need any errors that occurs throughout bulk DML processing to be thrown as an Apex exception that right now interrupts control waft (by using using strive. . .Trap blocks). This conduct is similar to the way exceptions are treated in most database procedural languages.
Use DML database strategies if you need to allow partial success of a bulk DML operation—if a report fails, the remainder of the DML operation can nonetheless succeed. Your software can then look at the rejected records and probably retry the operation. When the usage of this form, you can write code that never throws DML exception mistakes. Instead, your code can use the best outcomes array to judge success or failure. Note that DML database strategies additionally consist of a syntax that supports thrown exceptions, just like DML statements.
Q38. Other Than Soql And Sosl What Is Other Way To Get Custom Settings?
Other than SOQL or SOSL, Custom settings have their personal set of methods to access the report.
For instance:If there may be custom putting of name ISO_Country,
SO_Country__c code = ISO_Country__c.GetInstance(‘INDIA’);
//To return a map of statistics units defined for the custom object (all statistics within the custom object), //you will use:
Map<String,ISO_Country__c> mapCodes = ISO_Country__c.GetAll();
// display the ISO code for India
System.Debug(‘ISO Code: ‘+mapCodes.Get(‘INDIA’).ISO_Code__c);
//Alternatively you can return the map as a list:
List<String> listCodes = ISO_Country__c.GetAll().Values();
Q39. Will Below Query Work? Explain.
Select Count(identity), Name, Address__c From Opportunity Group By Name
Above query will throw an error.
Explanation: In Group by clause the columns decided on need to be both used in Group through clause or in aggregate functions. The Name discipline is neither used in combination techniques and in group through clause and consequently will result in mistakes “Malformed Query”.
Q40. Explain The Need Or Importance Of The Controller Extension.?
Controller extension is very useful and important concept delivered through the salesforce currently. It offers the power to programmer to increase the functionality of existing custom controller or widespread controller.
A Visualforce will have a single Custom controller or fashionable controller but many controller extensions.
We can say that the custom extension is the supporter of custom or popular controller.
Consider one instance: If there may be one controller written and utilized by the more than one visualforce pages and one of them desires a few greater good judgment. Then rather than writing that common sense to controller class (Which is utilized by many visualforce pages) we are able to create a controller extension and follow to that page simplest.
Q41. What Is A Visualforce Page?
Visualforce is the new markup language from salesforce, with the aid of the use of which, We can render the standard types of salesforce. We can nonetheless use HTML here in Visualforce. Each visualforce tag usually starts with “apex” namespace.
All the layout element can be acomplished by using the use of Visualforce Markup Language and the commercial enterprise good judgment can be written in custom controllers related to the Page.
Q42. Access Custom Controller-described Enum In Custom Component?
We can't reference the enum immediately for the reason that enum itself isn't always visible to the page and you can’t make it a assets.
Example:
Apex elegance:
global with sharing magnificence My_Controller
public Case currCase get; set;
public enum StatusValue RED, YELLOW, GREEN
public StatusValues getColorStatus()
go back StatusValue.RED; //demo code - just go back red
Visualforce web page:
<apex:image url='stopsign.Png' rendered="!ColorStatus == StatusValue.RED"/>
Above code snippet will throw errors some thing like “Save Error: Unknown property‘My_Controller.StatusValue’”
Resolution:
Add below method in Apex Controller:
public String currentStatusValue get return getColorStatus().Name();
and change Visualforce code to
<apex:image url='stopsign.Png' rendered="!CurrentStatusValue == 'RED'" />
Q43. It May Happen That Above Tips Will Not Work As Lots Of Time The Page Header Already Set. Then, How To Achieve Same Result Using Apex?
Add underneath line of code in Apex (Constructor)
Apexpages.CurrentPage().GetHeaders().Placed('X-UA-Compatible', 'IE=eight');
Q44. How To Display Error Message On Visualforce Page?
In the Visualforce web page add the tag:
<apex:pageMessages />
In the controller magnificence upload the mistake message where required
if ( requiredFieldName == null)
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Please enter a price inside the Required Field'));
Q45. Can We Create Master Detail Relationship On Existing Records?
No. As mentioned above, first we ought to create the lookup dating then populate the fee on all current record after which convert it.
Q46. How To Force Lead Assignment Rule Via Apex While Updating Or Adding The Lead?
To enforce Assignment Rules in Apex you may need to perform following steps:
@Instantiate the “Database.DMLOptions” class.
@Set the “useDefaultRule” property of “assignmentRuleHeader” to True.
@Finally name a native technique on your Lead called “setOptions”, with the Database.DMLOptions instance as the argument.
// to turn ON the Assignment Rules in Apex
Database.DMLOptions dmlOptn = new Database.DMLOptions();
dmlOptn.AssignmentRuleHeader.UseDefaultRule = actual;
leadObj.SetOptions(dmlOptn);
Q47. How To Round The Double To Two Decimal Places In Apex?
Decimal d = a hundred/three;
Double = d.SetScale(2);

