Tuesday, January 28, 2014

How to setup Field Level Security (FLS) for Person Account Fields. OR Why I am not able to find list of Person Account fields in Field Level Security (FLS) settings when navigated to fields on Account Object.

How to setup Field Level Security (FLS) for Person Account Fields.
OR

Why I am not able to find list of Person Account fields in Field Level Security (FLS) settings when navigated to fields on Account Object.

Field Level Security (FLS) of Person Account fields ar controlled by Contact Fields. So, if you want to setup FLS of Person Account Fields navigate to fields of Contact and it will be reflected on Person Account

How do you import Converted Lead into Salesforce from Legacy System

How do you import Converted Lead into Salesforce from Legacy System

Fields we need for importing converted leads are “ISCONVERTED” , “CONVERTEDCONTACTID” , “CONVERTEDOPPORTUNITYID” and “CONVERTEDACCOUNTID“.
Step 1 : As above fields are not editable, we have to contact Salesforce Support to enable Audit fields. Enabling Audit fields means we can edit few Readonly fields like created date and above lead fields.
Step 2 : Import Account, Contact and Opportunity from Legacy system to Salesforce.
Step 3 : If you imported account, contact and opportunity in Step 2, Salesforce automatically generates Unique ID. We need that unique Id to insert Converted Lead. So Export Account, Contact and Opportunity, which is inserted in Step 2 from legacy System.
Step 4 : Create CSV File with All lead information with ISCONVERTED=TRUE and CONVERTEDCONTACTID, CONVERTEDOPPORTUNITYID, CONVERTEDACCOUNTID. CONVERTEDCONTACTID, CONVERTEDOPPORTUNITYID and CONVERTEDACCOUNTID should correspond to Ids generated by Salesforce for Contact, Opportunity and Account which will be related to converted lead.
Step 5 : Once CSV is properly created with all required Data, Insert it using DataLoader.

Note : We cannot convert existing lead using this process. Leads must be inserted with these four fields. If you try to update lead it will not give you option to edit above fields 

After Data Export using DataLoader, Some time it appears that data is on New Line (Carriage Return) when we open CSV file in Microsoft Excel. For example , Address Data separated on different lines. How can we override this problem

After Data Export using DataLoader, Some time it appears that data is on New Line (Carriage Return) when we open CSV file in Microsoft Excel. For example , Address Data separated on different lines. How can we override this problem

Excel does all sorts of “useful” things when it opens a CSV file. It will re-format dates, strip leading zeros, corrupt record IDs (if you have them in your report), and as explained it will also break line. Best way as per my experience till date is, Upload document to Google Drive. Export document back from Google drive as Excel.

Please post comment in this article if you know any other working way.
  

How you can use Datetime field as a criteria in SOQL Query

How you can use Datetime field as a criteria in SOQL Query

We cannot use Datetime as condition in Where Clause in between single Quotes.
You can do something like this ,

WHERE CreatedDate > 2005-10-08T00:00:00Z
Or, you can also use Date Literals like

WHERE CreatedDate > YESTERDAY
For more information on date formats and more literal values, check this URL.
Sample:
soql += ' and Name LIKE \''+String.escapeSingleQuotes(key1)+'%\''; - not required single quote like this.
  

While creating Dynamic SOQL, which involves Datetime gives ” no viable alternative at character ‘’ ” error. OR value of filter criterion for field ‘CreatedDate’ must be of type dateTime and should not be enclosed in quotes OR How to use Datetime in Dynamic SOQL Query in Salesforce

While creating Dynamic SOQL, which involves Datetime gives ” no viable alternative at character ‘<EOF>’ ” error.
OR
value of filter criterion for field ‘CreatedDate’ must be of type dateTime and should not be enclosed in quotes
OR
How to use Datetime in Dynamic SOQL Query in Salesforce

This error is because of wrong construction of Dynamic Query with Datetime. following code snippet will give idea on how to construct dynamic query for Datetime ?
//format the datetime to make it Dynamic Soql ready
String formatedDt = cutOffDateTime.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
String sql = 'SELECT  a.Id  FROM  Agents_Answer__c a    WHERE  a.Agents_Test_Result__r.Agent_Name__r.IsActive__c = false AND  LastModifiedDate < '+ formatedDt ;

Where, “cutOffDateTime” is variable of datetime type. 

Can we mass delete reports using Apex (Anonymous Apex)

Can we mass delete reports using Apex (Anonymous Apex)

Salesforce has not exposed any API for Reports. So best way is :

Move all reports needs to delete in new folder.
Inform everyone that reports will be deleted after some time may be 30 days.
Import your reports folder in Eclipse including all reports to be deleted and then delete the the reports folder in eclipse. It will delete all the reports at once.
  

In below code snippet , What is your observation and what is going wrong ? * trigger TestBeforeDelete on Lead (before Delete) { for(Lead l : Trigger.Old) { l.addError('error'); } String msgBody = 'Test Email'; String Subject = 'Test from Cogni Force on Lead'; Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {'abc@gmail.com'}; mail.setToAddresses(toAddresses); mail.setReplyTo('abc@gmail.com'); mail.setSenderDisplayName('Cogniforce Test Simulator'); mail.setSubject(Subject); mail.setPlainTextBody(msgBody); mail.setHTMLBody(msgBody); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); }

In below code snippet , What is your observation and what is going wrong ? *
trigger TestBeforeDelete on Lead (before Delete) {

        for(Lead l : Trigger.Old)
        {
            l.addError('error');
        }

        String msgBody = 'Test Email';
        String Subject = 'Test from Cogni Force on Lead';
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'abc@gmail.com'};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('abc@gmail.com');
        mail.setSenderDisplayName('Cogniforce Test Simulator');
        mail.setSubject(Subject);
        mail.setPlainTextBody(msgBody);
        mail.setHTMLBody(msgBody);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

}

It will not send any email. Because “adderror” prevents all transactions from committing including emails

Why are Visualforce pages served from a different domain

Why are Visualforce pages served from a different domain

If we see carefully, all our Visualforce pages are served like “c.YOURSERVER.visual.force.com/apex/YOURPAGENAME” ,
And because of this most of time we run into Same-Origin Policy error in Javascripyt if we try to access parent page from Iframe. Following reason is explained by one of the evangelist of Salesforce:

“The move to separate domains has one very specific purpose: leverage the browser security model (same domain policy) to protect our customers and the salesforce.com service from cross site scripting and cross site request forgery attacks.

Moving to the serving pages from separate domains is a critical component of our ongoing commitment to insure the highest level of security and availability for everyone.

In the world where everything is served from the same domain any custom page that you visit had full access to any other page in your org and also any page served from salesforce.com itself. This included potentially malicious code that was installed as part of a force.com package.”


Sometimes while deleting record it gives error “Object cannot be Deleted”. What is the reason for this kind of error

Sometimes while deleting record it gives error “Object cannot be Deleted”. What is the reason for this kind of error

This is generic error message prompted by Salesforce many times, which is not well informative. To get informative message, we can try to delete same record in “Developer Console”. In Developer Console Debug log, we will get exact error message.
Example : Lets say there is one record which is parent of more than 2000 records and grand parent of 5000 records. In such scenario from developer console it gives error something like “record cannot be deleted because it has many associated objects” However in User Interface, it will just display that “Object cannot be deleted.“ 

Explain few considerations for @Future annotation in Apex

Explain few considerations for @Future annotation in Apex

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 

Explain Considerations for Static keyword in Apex

Explain Considerations for Static keyword in Apex

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.


What is difference between public and global class in Apex

What is difference between public and global class in Apex

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.
global class MySchedulableClass implements Schedulable {} - schedular class
global class UpdateController {
webService static string updateEnable(List<Id> accId){}
} - javascript remoting

global class MyWebService {
    webService static Id makeContact(String lastName, Account a) {
        Contact c = new Contact(lastName = 'Weissman', AccountId = a.Id);
        insert c;
        return c.id;
    }
} 

How can you call Apex class using Javascript ? Give Example

 How can you call Apex class using Javascript ? Give Example

global class myClass {
                webService static Id makeContact (String lastName, Account a) {
                                Contact c = new Contact(LastName = lastName, AccountId = a.Id);
                                Insert c;
                                return c.id;
                }
}

we can execute above method from javascript like :
var account = sforce.sObject("Account");
var id = sforce.apex.execute("myClass“ , "makeContact",
{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;



What are few Considerations about Trigger

What are few Considerations about Trigger

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 

What are few limitations (points to remember) of Savepoint or Transaction Control in Apex

What are few limitations (points to remember) of Savepoint or Transaction Control in Apex

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.
  

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

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

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.
  

How can you lock record using SOQL so that it cannot be modified by other user

How can you lock record using SOQL so that it cannot be modified by other user

we will need “FOR UPDATE” clause of SOQL.
Sample :
Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];


Which SOQL statement can be used to get all records even from recycle bin or Achieved Activities

Which SOQL statement can be used to get all records even from recycle bin or Achieved Activities

We will need “ALL Rows” clause of SOQL.
Sample :
SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS


Give Sample Code Snippet of Apex that that will show that how Parent and Child record can be inserted in Single Statement

Give Sample Code Snippet of Apex that that will show that how Parent and Child record can be inserted in Single Statement

It can be done with help of External Id.
Date dt = Date.today().addDays(7);
Opportunity newOpportunity = new Opportunity(Name = 'shivasoft', StageName = 'Prospecting', CloseDate = dt);

/*
Create 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

System.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: []
*/

Account accountReference = new Account(MyExtID__c = 'SHIVA1234567');
newOpportunity.Account = accountReference;

//  Create the Account object to insert.  Same as above but has Name field.  Used for the insert.
Account parentAccount = new Account(Name = 'Shiva', MyExtID__c = 'SHIVA1234567');

Database.SaveResult[]
    results = Database.insert(new SObject[] {  parentAccount, newOpportunity });
  

Difference in “Export” and “Export All” in Data Loader in Salesforce

Difference in “Export” and “Export All” in Data Loader in Salesforce


Export : It is used to export the Salesforce Data(excluding recycle bin’s data) into your local system.

Export All :  It is used to export the Salesforce Data(including recycle bin’s data) into your local system.


In Master Detail Relationship : OWD for Parent is public Read Only. If User has – Create, Edit Permission on Master as well as Detail Object. While creating record for detail object he selects parent record which is not created by him. What will happen in this case ?

In Master Detail Relationship :
OWD for Parent is public Read Only.
If User has – Create, Edit Permission on Master as well as Detail Object. 

While creating record for detail object he selects parent record which is not created by him. What will happen in this case ?

He will get an error, because in order to add child record user must have edit permission in parent master record

How to handle comma within field while uploading using DataLoader

How to handle comma within field while uploading using DataLoader

Data Loader cannot handle this implicitly because there is no logical path to follow. In case your Data Loader CSV file for import will contain commas for any of the field content, you will have to enclose the contents within double quotation marks ” “. Data Loader will be able to handle this.

For example :
Column_1__c,Column_2__c,Column_3__c
Shiva,"Jitendra, Minal",Soft

If you are creating the import CSV in Excel, the quotation marks will be inserted automatically by Excel whenever a comma is detected in any cell – Saving the CSV in Excel and opening the same in Notepad reveals the enclosing quotation marks for cells containing commas.
  

How to convert carriage returns in Textarea to Line Breaks in Visualforce

How to convert carriage returns in Textarea to Line Breaks in Visualforce

We can use “<apex:outputField>” instead of “<apex:outputText>”. It will maintain formatting automatically 

Once you convert lead, Few fields on lead should be reset so that sensitive information should not be queried using SOQL. How to get this done

Once you convert lead, Few fields on lead should be reset so that sensitive information should not be queried using SOQL. How to get this done

Once lead is converted, its READ ONLY. we cannot update it using Apex or Trigger. However we can use “Before Update” trigger on lead and check for fiels “IsConverted“. If its true means lead is going to be converted so reset all fields in that case

System admin has created a Visualforce for Account. In future he created few more new Fields. How could System admin can code Visualforce so that in future if any new field is added or existing field deleted. It should reflect in Visualforce without changing anycode

System admin has created a Visualforce for Account. In future he created few more new Fields. How could System admin can code Visualforce so that in future if any new field is added or existing field deleted. It should reflect in Visualforce without changing anycode

It can be done with help of Field Sets. Please read this article.
Case - 1
public class MerchandiseDetails {

    public Merchandise__c merch { get; set; }
   
    public MerchandiseDetails() {
        this.merch = getMerchandise();
    }

    public List<Schema.FieldSetMember> getFields() {
        return SObjectType.Merchandise__c.FieldSets.Dimensions.getFields();
    }

    private Merchandise__c getMerchandise() {
        String query = 'SELECT ';
        for(Schema.FieldSetMember f : this.getFields()) {
            query += f.getFieldPath() + ', ';
        }
        query += 'Id, Name FROM Merchandise__c LIMIT 1';
        return Database.query(query);
    }
}
<apex:page controller="MerchandiseDetails">
    <apex:form >

      <apex:pageBlock title="Product Details">
          <apex:pageBlockSection title="Product">
              <apex:inputField value="{!merch.Name}"/>
          </apex:pageBlockSection>
     
          <apex:pageBlockSection title="Dimensions">
              <apex:repeat value="{!fields}" var="f">
                  <apex:inputField value="{!merch[f.fieldPath]}"
                      required="{!OR(f.required, f.dbrequired)}"/>
              </apex:repeat>
          </apex:pageBlockSection>
 
        </apex:pageBlock>

    </apex:form> 
</apex:page>

Case - 2
<apex:page standardController="Contact">
    <apex:repeat value="{!$ObjectType.Contact.FieldSets.properNames}" var="f">
        <apex:outputText value="{!Contact[f]}" /><br/>
    </apex:repeat>
</apex:page>


How to get total number of Child records in Lookup relationship

How to get total number of Child records in Lookup relationship

As Rollup Summary field is only supported in Master detail, we cannot use it for Lookup. There are following two ways (If anyone has any other idea please comment).

Inline Visualforce page
Trigger on Child Object, which will update field in Parent record if child record is inserted, deleted or undeleted

How to get Ip Address of User in Apex

How to get Ip Address of User in Apex

String ipAddress = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');

True-Client-IP has the value when the request is coming via the caching integration.
X-Salesforce-SIP has the value if there is no caching integration (sandbox, developer edition orgs) or via the secure url.
Thanks to TechNrd for this tips.


Why CSS is not working in PDF created by Visualforce

Why CSS is not working in PDF created by Visualforce

In Many cases, i have observed problems faced by my colleagues and complaining that CSS is not working when they try to render any Visualforce page as “PDF”. Same Question is asked many times in Interviews also. Basically there are two ways:

Use “apex:stylesheet” tag to import external CSS file
Wrap “Style” tag inside “Head” tag in Visualforce
  

User Wants to set the starting day in Calendar as “Monday” instead of “Sunday”. How to get it done

User Wants to set the starting day in Calendar as “Monday” instead of “Sunday”. How to get it done

Change the user locale to “English ( United Kingdom ) ” in Personal information or User record.


User have all the permissions to see the Dashboard and Source Folder still when he wants to see dashboard, its not visible. What might be the cause

User have all the permissions to see the Dashboard and Source Folder still when he wants to see dashboard, its not visible. What might be the cause

It is possible that Salesforce User license for Dashbaord running user is different than User wants to access Dashboard. Example – Running User license is “Salesforce” and user trying to access Dashboard is “Salesforce Plateform”

What is the difference between “apex:dataTable” and “apex:pageBlockTable” components in Visualforce

What is the difference between “apex:dataTable” and “apex:pageBlockTable” components in Visualforce

Both component is used to render data in tabular format. dataTable will render records in simple HTML table format whereas the “pageBlockTable” possess default look and feel of salesforce standard CSS and must be written inside “apex:pageBlock” componet.
You can read more here.

PageBlockTable:
PageBlockTable should be defined inside pageblock or pageblocksection.
PageBlockTable uses standard styles sheets to design a visualpage.
It has the  required attribute "value".
Column headers  will be displayed automatically.

DataTable:
No need to write inside pageblock or pageblocksection.
There is no required value.
The  data can be displayed using  custom style sheets.

we need to specify column headers explicitly.

What is the use of apex:detail component

What is the use of apex:detail component

: With the help of this Visualforce component, we can diretly get complete behavior of page layout defined for logged in users profile. There is no need to add fields, related lists explicitly. Read more here.
https://na3.salesforce.com/apex/AccountDisplay?id=0018000000MDfn1
<apex:page standardController="Account">
    <apex:detail/>
</apex:page>

You can show only a particular related list; such as the list of case records that are related to the account record you are viewing. Add the following tag:
<apex:relatedList list="Cases" />
  

In how many ways you can invoke Controllers / Controller Extensions method from VF

In how many ways you can invoke Controllers / Controller Extensions method from VF

Javascript Remoting, ActionFunction, ActionSupport, ActionPoller.
var Attachrecords = sforce.connection.query(strQuery); 

var result = sforce.apex.execute("UpdateController", "updateEnable",{accId: accountId}); 

Explain ActionFunction, ActionSupport and ActionPoller in Visualforce

Explain ActionFunction, ActionSupport and ActionPoller in Visualforce

apex:ActionFunction : This component helps to envoke AJAX request (Call Controllers method) directly from Javascript method. It must be child of apex:form. Read here – www.salesforce.com/us/developer/docs/pages/Content/pages_compref_actionFunction.htm
<apex:actionFunction name="sendEmail" action="{!sendEmailFunction}"></apex:actionFunction>

apex:ActionSupport : This component adds Ajax request to any other Visualforce component. Example : Commandlink button has inbuilt AJAX functionality however few components like OutputPanel does not have inbuilt AJAX capabilities. So with the help of this component, we can enable AJAX. Read more here.
<apex:outputpanel id="counter">
<apex:outputText value="Click Me!: {!count}"/>
<apex:actionSupport event="onclick"  action="{!incrementCounter}"  rerender="counter" status="counterStatus"/>
</apex:outputpanel>

apex:ActionPoller : This is timer component which can send AJAX request on pre-defined interval. Minimum interval is 5 sec and default is 60 sec.
<apex:actionPoller action="{!incrementCounter}" rerender="counter" status="counterStatus" interval="50" />

Similarities:
Both action support and function can be used to call a controller method using an AJAX request.

Differences:
1. Action function can call the controller method from java script.
2. Action support adds AJAX support to another visualforce component and then call the controller method.
    for example:
     <apex:outputpanel id="outptpnl">
             <apex:outputText value="click here"/>
         <apex:actionSupport event="onclick" action="{!controllerMethodName}"  rerender="pgblck" />
     </apex:outputpanel>   
Here action support adds AJAX to output panel, so once you click on output panel controller method will be called.
3. Action function cannot add AJAX support to another component. But from a particular component which has AJAX support(onclick, onblur etc) action function can be called to call the controller method.
Example:
 <apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/>
 <apex:inputcheckbox onclick="myactionfun" />
In this example onlick of input checkbox "myactionfun" action function is called from where controller method "actionFunMethod" gets called.

Apart from this, the main difference between the "two" action support and action function is that, the action function can also be called from java script.
Example:
<apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/>
 <apex:inputcheckbox onclick="myJavaMethod()" />
<script>
   function myJavaMethod(){
     myactionfun();// this call the action function
  }
  </script>



Monday, January 27, 2014

While trying to access javascript code from some CDN like Google, we get error something like “attempt to run uG request”. How to resolve it

While trying to access javascript code from some CDN like Google, we get error something like “attempt to run uG request”. How to resolve it

While providing URL, do not specify the protocol. Use like this:
<script type='text/javascript' src= '//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script> 

System.debug() statements are included against script count

System.debug() statements are included against script count

Any statement ending with semi-colon will be included against script count. There is very good article by Abhinav explaining this here.


When loading data into date fields such as Opportunity Close Date using the Data Loader, the date displayed in the application is sometimes one day earlier than the date in the file. What may be the reason and solution

When loading data into date fields such as Opportunity Close Date using the Data Loader, the date displayed in the application is sometimes one day earlier than the date in the file. What may be the reason and solution

The reason for this is that fields such as Close Date are actually date/time fields. When a date is loaded without specifying the time, the time is defaulted to 00:00 – midnight. When another user is in a time zone which is behind the current user’s time zone, the date will show on the previous day. For example:

20 August 2008 00:00 in Paris is 19 August 2008 23:00 in London

Similar issues can arise when daylight savings time begins or ends.

Two simple solutions to this are:
1) Specify a time as well as a date when loading dates using the Data Loader.
or
2) Switch your PC’s time zone to Hawaiian time before starting up the Data Loader.
  

Let’s say we have to update the same record in After Trigger context. Is there any way or workaround

Let’s say we have to update the same record in After Trigger context. Is there any way or workaround

If we create a new instance of an SObject in the Apex Trigger in memory using the Id of the newly created record as provided in the After Trigger context, we can perform an Update DML statement and not get a read only error. This is because in Apex, the SObject is seen as a new reference (even though the records have the same SFDC ID) and therefore is eligible for DML operations. The below snippet of code illustrated this working and not working.
List<Contact> originals = new List<Contact>();
if(mirrorResultMap.values().size() > 0)
{
                for(Contact origContact : contactRecs.values())
                {
                                Contact mirrorContact = mirrorResultMap.get(origContact.Id);
                                //origContact.Linked_Contact__c = mirrorContact.Id; //Link the Original Record tot he Mirror Record WILL FAIL
                                Contact origContactUpdate = new Contact(Id=origContact.Id, Linked_Contact__c = mirrorContact.Id); //This will WORK
                                originals.add(origContactUpdate);
                }
                //update contactRecs.values(); //Update the Records -> THIS WILL FAIL AS ITS ORIGINAL RECORDS IN MEMORY
                update originals;
}
Credit goes to Cory Cowgill for this Blog Entry.


What will happen if you try to update record in After Trigger Context

What will happen if you try to update record in After Trigger Context

You will get an error saying “record is Read only

What will happen if you try to update record in After Trigger Context

What will happen if you try to update record in After Trigger Context

You will get an error saying “record is Read only”.

In trigger, lets say we have system.debug() statement after adderror() method. Will system.debug() be statement executed in Trigger after adderror() method

In trigger, lets say we have system.debug() statement after adderror() method. Will system.debug() be statement executed in Trigger after adderror() method

adderror() method is not error statement rather its normal execution flow and all the statements written after adderror() will be executed normally.

While creating workflow on Task, what difference observed on available actions

While creating workflow on Task, what difference observed on available actions

“Send Email”(email alert) action is not available while creating workflow on task

How to clear the Time based workflow action queue

How to clear the Time based workflow action queue

Two ways to achieve this : 1. Make criteria false for all those records. 2. Navigate to “Set up | Monitoring | Time Based Workflow”, search for scheduled actions and remove from queue.
  

How to clear the Time based workflow action queue

How to clear the Time based workflow action queue

Two ways to achieve this : 1. Make criteria false for all those records. 2. Navigate to “Set up | Monitoring | Time Based Workflow”, search for scheduled actions and remove from queue.
  

We have “Time Based Workflow” and there is action scheduled to be executed. Can we delete that workflow

We have “Time Based Workflow” and there is action scheduled to be executed. Can we delete that workflow

If a workflow have any pending time dependent action, then we cannot delete the workflow.


We have a “Time Based Workflow” and there is Action scheduled to be executed. If we Deactivate the workflow, Scheduled actions will be removed from queue or not

We have a “Time Based Workflow” and there is Action scheduled to be executed. If we Deactivate the workflow, Scheduled actions will be removed from queue or not

Even after deactivation of workflow, its action will be active in queue.


Lets consider you had created outbound changeset previously. After that, some class is modified which is part of that old changeset. If you clone that Changeset, current updated class will be included or that previous class will be included in changset

Lets consider you had created outbound changeset previously. After that, some class is modified which is part of that old changeset. If you clone that Changeset, current updated class will be included or that previous class will be included in changset

Once changeset is created it cannot be modified. After creation of changset, if we modify any component it will not reflected and when we clone the changeset, all components (offcource old copy of component) will be added to changeset

In Custom Component How we can return value to Custom Controller or Controller Extension

In Custom Component How we can return value to Custom Controller or Controller Extension

In Apex, Objects are passed by reference (read this article to understand Pass by Value and Pass by reference in Salesforce and also read this Salesforce blog article). So supply an argument of wrapper class (object) type to custom component. If its value is changed in Custom component we will get updated value in controller also.


In Ajax toolkit for custom Javascript button, you have to explicitly login to API because global Session variable is not available. In that case it is security vulnerable because anybody logged in can see the javascript code and your username and password. So is there any way to avoid this

In Ajax toolkit for custom Javascript button, you have to explicitly login to API because global Session variable is not available. In that case it is security vulnerable because anybody logged in can see the javascript code and your username and password. So is there any way to avoid this

We can create a visualforce page with output type as JavaScript. Global session variable is available in VF page. Initialize the global javascript variable in that VF page. include VF page as a javascript file and we are done!

How to get selected records ID from List View using Javascript / Ajax Toolkit, when custom button is added on List View page

How to get selected records ID from List View using Javascript / Ajax Toolkit, when custom button is added on List View page

Create a new Button on Lead of type List Button. Add the button on Lead List View Layout and write below Javascript code:
{!RequireScript("/js/functions.js")}

var recordsSelected = {!GetRecordIds($ObjectType.Lead)}
for(var i=0; i < recordsSelected .length ; i++) {
     alert('Selected ID '+recordsSelected[i]);

}

Consider we have overall 90% code coverage however there is one class which have 0% code coverage. Can we still able to deploy that class on production

Consider we have overall 90% code coverage however there is one class which have 0% code coverage. Can we still able to deploy that class on production

Yes. Minimum 1% required for every trigger and there is no such restriction for Apex class

Can you use aggregate expressions inside inner query? Explanation – Can you use Group by clause inside inner query in SOQL? Example : Something like : SELECT Id, Name,(SELECT Count(Id),Name FROM Contacts Group By Name Having count(Id) > 1 ) FROM Account

Can you use aggregate expressions inside inner query?
Explanation – Can you use Group by clause inside inner query in SOQL?
Example : Something like :
SELECT Id, Name,(SELECT Count(Id),Name FROM Contacts Group By Name Having count(Id) > 1 ) FROM Account



No. only root queries support aggregate expressions. Return type is List<AggregateResult> for above query However the root result expects List<Account> and there is no syntax or provision available in Salesforce to specify that child results are of type “AggregateResult“.