Formula

Formula: A read-only field that derives its value from a formula expression that we define. The formula field is updated when any of the source fields change.
Rollup Summary: A read-only field that displays the count,sum, minimum, or maximum value of a field in a related list or the record count of all records listed in a related list.


Deployment fails with duplicate value found: duplicates value on record with id: error

Summary
Metadata Deployment fails if there is history tracking in custom lookup field with look up filters, when the filter refers to a field with tracking to custom object in the same deployment transaction.
Repro
1) Create a custom object foo__c with a custom field field a__c and enable history for the object and track the history for the field.

2) Create a custom object bar__c with a custom look up field b__c, where b__c has a look up filter foo__c.a__c, history is enabled for the object and history tracking is enabled for the field b__c.

3) Deploy the package including the two objects and there is an error : duplicate value found: <unknown> duplicates value on record with id: <unknown>
Workaround
a) Deploy both the objects in different transactions so there is no error.

b) Remove the History Tracking on the custom field and then deploy. Once the deployment is completed, history tacking can be enabled on the custom filed as part of post deployment step.
c) Remove the components(fields and objects) if already deployed

What is a Wrapper Class in S.F?

 A wrapper class is a class whose instances are collections of other objects like primitive data type,non-primitive type,salesforce object and user defined data types

Why are Milestones not showing up even if the milestone criteria is met correctly??

There are occasions where milestone is not evaluated even if  the milestone criteria is met correctly

The scenario is the milestone criteria is met by the field updates of past milestone action.  For example,  there are two milestones in place.  The first one will be triggered first and subsequently change the field via violation actions, which will meet the criteria of the second milestone.    It is currently working as designed.  Milestones are not evaluated by milestone actions(such as Success Actions, Warning Actions and Violation Actions)

Resolution:
There are a few working around for this limitation
  1. Manually edit and save the record to trigger milestones
  2. User different criteria among milestones
  3. Utilize Apex/API to update the record

chatter_answers_question_escalation_to_case_trigger: trigger body is invalid and failed recompilation: Entity is not org-accessible Stack Trace: null

Answer by Salesforce Support:

The team has been working to no longer enable Chatter Answers for new or upgraded customer orgs beginning with Summer '16 [Release notes: https://releasenotes.docs.salesforce.com/en-us/summer16/release-notes/rn_networks_chatter_answers_retire.htm ].

Some time after the release went live, it came to our attention that provisioning processes were disabling the Chatter Answers feature for existing orgs. Once the bug was diagnosed, the team was able to re-enable some affected customers through a database script, and later released a permanent fix to the issue.

The fix entailed making changes which will exclude this permission from being affected by provisioning. Furthermore, the feature permissions are now accessible for manual enablement by Customer Support.

Way to solve:
     Log a case to salesforce support

Code Coverage Best Practices

Code Coverage General Tips

  1. Run tests to refresh code coverage numbers. Code coverage numbers aren't refreshed when updates are made to Apex code in the organization unless tests are rerun.
  2. If the organization has been updated since the last test run, the code coverage estimate can be incorrect. Rerun Apex tests to get a correct estimate.
  3. The overall code coverage percentage in your organization doesn’t include code coverage from managed package tests. The only exception is when managed package tests cause your triggers to fire. For more information, seeManaged Package Tests.
  4. Coverage is based on the total number of code lines in the organization. Adding or deleting lines of code changes the coverage percentage. For example, let's say an organization has 50 lines of code covered by test methods. If you add a trigger that has 50 lines of code not covered by tests, the code coverage percentage drops from 100% to 50%. The trigger increases the total code lines in the organization from 50 to 100, of which only 50 are covered by tests.

Why Code Coverage Numbers Differ between Sandbox and Production

When Apex is deployed to production or uploaded as part of a package to the Force.com AppExchange, Salesforce runs local tests in the destination organization. Sandbox and production environments often don’t contain the same data and metadata, so the code coverage results don’t always match. If code coverage is less than 75% in production, increase the coverage to be able to deploy or upload your code.
The following are common causes for the discrepancies in code coverage numbers between your development or sandbox environment and production. This information can help you troubleshoot and reconcile those differences.
1.Test Failures
If the test results in one environment are different, the overall code coverage percentage doesn’t match. Before comparing code coverage numbers between sandbox and production, make sure that all tests for the code that you’re deploying or packaging pass in your organization first. The tests that contribute to the code coverage calculation must all pass before deployment or a package upload.
2.Data Dependencies
If your tests access organization data by using the @isTest(SeeAllData=true) annotation, the test results can differ depending on which data is available in the organization. If the records referenced in a test don’t exist or have changed, the test fails or different code paths are executed in the Apex methods. Modify tests so that they create test data instead of accessing organization data.
3.Metadata Dependencies
Changes in the metadata, such as changes in the user’s profile settings, can cause tests to fail or execute different code paths. Make sure that the metadata in sandbox and production match, or ensure that the metadata changes aren’t the cause of different test execution behavior.
4.Managed Package Tests
Code coverage that is computed after you run all Apex tests in the user interface, such as the Developer Console, can differ from code coverage obtained in a deployment. If you run all tests, including managed package tests, in the user interface, the overall code coverage in your organization doesn’t include coverage for managed package code. Although managed package tests cover lines of code in managed packages, this coverage is not part of the organization’s code coverage calculation as total lines and covered lines. In contrast, the code coverage computed in a deployment after running all tests through the RunAllTestsInOrg test level includes coverage of managed package code. If you are running managed package tests in a deployment through the RunAllTestsInOrg test level, we recommend that you run this deployment in a sandbox first or perform a validation deployment to verify code coverage.
5.Deployment Resulting in Overall Coverage Lower Than 75%
When deploying new components that have 100% coverage to production, the deployment fails if the average coverage between the new and existing code doesn’t meet the 75% threshold. If a test run in the destination organization returns a coverage result of less than 75%, modify the existing test methods or write additional test methods to raise the code coverage over 75%. Deploy the modified or new test methods separately or with your new code that has 100% coverage.
6.Code Coverage in Production Dropping Below 75%
Sometimes the overall coverage in production drops below 75%, even though it was at least 75% when the components were deployed from sandbox. Test methods that have dependencies on the organization’s data and metadata can cause a drop in code coverage. If the data and metadata have changed sufficiently to alter the result of dependent test methods, some methods can fail or behave differently. In that case, certain lines are no longer covered.

Recommended Process for Matching Code Coverage Numbers for Production

  1. Use a Full Sandbox as the staging sandbox environment for production deployments. A Full Sandbox mimics the metadata and data in production and helps reduce differences in code coverage numbers between the two environments.
  2. To reduce dependecies on data in sandbox and production organizations, use test data in your Apex tests.
  3. If a deployment to production fails due to insufficient code coverage, write more tests to raise the overall code coverage to the highest possible coverage or 100%. Retry the deployment.
  4. If a deployment to production fails even after you raise code coverage numbers in sandbox, run local tests from your production organization. Identify the classes with less than 75% coverage. Write additional tests for these classes in sandbox to raise the code coverage.

Testing Best Practices || Test Classess Best Practice


  1. Cover as many lines of code as possible.
    1. At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully
    2. When deploying Apex to a production organization, each unit test in your organization namespace is executed by default.
    3. Calls to System.debug are not counted as part of Apex code coverage
    4. Test methods and test classes are not counted as part of Apex code coverage.
    5. 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.
    6. Every trigger must have some test coverage.atleast 1% coverage.
    7. All classes and triggers must compile successfully.
  2. If code uses conditional logic (including ternary operators), execute each branch.
  3. Make calls to methods using both valid and invalid inputs.
  4. Complete successfully without throwing any exceptions, unless those errors are expected and caught in a trycatch block.
  5. Always handle all exceptions that are caught, instead of merely catching the exceptions.
  6. Use System.assert methods to prove that code behaves properly.
  7. Use the runAs method to test your application in different user contexts.
  8. Exercise bulk trigger functionality—use at least 20 records in your tests.
  9. Use the ORDER BY keywords to ensure that the records are returned in the expected order.
  10. Not assume that record IDs are in sequential order:Record IDs are not created in ascending order unless you insert multiple records with the same request. For example, if you create an account A, and receive the ID 001D000000IEEmT, then create account B, the ID of account B may or may not be sequentially higher.
  11. Set up test data:
    1. Create the necessary data in test classes, so the tests do not have to rely on data in a particular organization.
    2. Create all test data before calling the Test.startTest method.
    3. Since tests don't commit, you won't need to delete any data.
  12. Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the expected outcome, and so on.
  13. Test the classes in your application individually. Never test your entire application in a single test.
  14. If you are running many tests, consider the following:
    1. In the Force.com IDE, you may need to increase the Read timeout value for your Apex project. Seehttps://developer.salesforce.com/page/Apex_Toolkit_for_Eclipse for details.
    2. In the Salesforce user interface, you may need to test the classes in your organization individually, instead of trying to run all the tests at the same time using the Run All Tests button.

Best Practices for Parallel Test Execution*

Tests that are started from the Salesforce user interface (including the Developer Console) run in parallel. Parallel test execution can speed up test run time. Sometimes, parallel test execution results in data contention issues, and you can turn off parallel execution in those cases. In particular, data contention issues and UNABLE_TO_LOCK_ROW errors might occur in the following cases:
  • When tests update the same records at the same time. Updating the same records typically occurs when tests don’t create their own data and turn off data isolation to access the organization’s data.
  • When a deadlock occurs in tests that are running in parallel and that try to create records with duplicate index field values. A deadlock occurs when two running tests are waiting for each other to roll back data, which happens if two tests insert records with the same unique index field values in different orders.
You can prevent receiving those errors by turning off parallel test execution in the Salesforce user interface:
  1. From Setup, enter Apex Test.
  2. Click Options....
  3. In the Apex Test Execution Options dialog, select Disable Parallel Apex Testing and then click OK.
Apex Test Execution Options

 

GetRecordTypeId without SOQL

public static id GetRecordTypeId(string objectAPIName, string recordTypeName)
    {
        Map<String, Schema.SObjectType> sobjectSchemaMap;
        if(String.isBlank(objectAPIName) || String.isBlank(recordTypeName))
        {
            return null;
        }
        if(sobjectSchemaMap == null)
        {
            sobjectSchemaMap = Schema.getGlobalDescribe();
        }
        Schema.SObjectType sObjType = sobjectSchemaMap.get(objectAPIName) ;
        
        Schema.DescribeSObjectResult cfrSchema = sObjType.getDescribe() ;
        
        Map<String,Schema.RecordTypeInfo> RecordTypeInfo = cfrSchema.getRecordTypeInfosByName();
        Id recordTypeId = RecordTypeInfo.get(recordTypeName).getRecordTypeId();
        return recordTypeId;
    }

Type of Visual Workflow (Flows) || Flow Types || Standard Flow Types

A flow or flow version’s type determines which elements and resources are supported, as well as the ways that the flow can be distributed.
The following flow types are supported in the Cloud Flow Designer.


  1. Flow: Requires user interaction, because it has one or more screens, steps, choices, or dynamic choices. This flow type doesn’t support wait elements. Flow A flow can be implemented with a custom button, custom link, direct URL, Visualforce page, or Salesforce1 action
  2. Autolaunched Flow:Doesn’t require user interaction. This flow type doesn’t support screens, steps, choices, or dynamic choices. Autolaunched Flow An autolaunched flow can be implemented any way that a flow can, as well as with a process action, workflow action (pilot), or Apex code.
  3. User Provisioning Flow:Provisions users for third-party services. A user provisioning flow can only be implemented by associating it with a connected app when running the User User Provisioning Flow Provisioning Wizard. Provisions users for third-party services. For example, use this flow type to customize the user provisioning configuration for a connected app to link Salesforce users with their Google Apps accounts 

Create PriceBook || Product || PricebookEntry || OpportunityLineItem(Opportunity Product)

When we create an Opportunity Line Item we basically link PricebookEntry record and Opportunity Record by creating a junction names OpportunityLineItem.So every time if we want to update unitprice(salesprice) price for OLI we need to update pricebook entry record since unit price is of Pricebook entry field and Total price is of OLI field.

1.Create a PriceBook
pricebook2 pb=new pricebook2();
pd.name='MyPriceBook';
pb.isActive=true;
insert pb;
2.Create a Product
Product2 prod = new Product2();
prod.Name = 'MyProduct';
prod.ProductCode = 'MyProduct';
prod.isActive = true;
insert prod;
3.Add(Link) a product to Pricebook
PricebookEntry pbEntry = new PricebookEntry();
pbEntry.Pricebook2Id = pricebookId;
pbEntry.Product2Id = prod.Id;
pbEntry.UnitPrice = 100.00;
pbEntry.IsActive = true;
insert pbEntry;
4.Create(Add) Opportunity Line Item(Opportunity Product).This assumes  already have an opportunity created
OpportunityLineItem oli = new OpportunityLineItem(
OpportunityId = opp.Id;
Quantity = 5;
PricebookEntryId = pbEntry.Id;
TotalPrice =123;
insert oli;

Passing Objects to Future Annotated Methods

One of the restrictions of future annotations is that you can not pass sObjects or objects as arguments to the annotated method.

public class clsForAllFutureMethods
{
  @future
  public static void FirstFutureMethod(List<String> lst)
  {
  }

}

But there is a way we can pass using  JSON serialize|deserialize methods.

public class wrapperClass{

 public Contact objContact{set; get;}
 public String AccountName{set; get;}
 public String OpportunityName{set; get;}
 

    public wrapperClass(Contact con, String aName, String oName) {
     objContact= con;
     aName = AccountName;
     oName= OpportunityName;
    }
}

---------------------------------------------------------------------------
List<String> lstString= new List<String>();
wrapperClass objWrap1= new wrapperClass(new Contact(LastName='Contact1'), 'Account1', 'Opp 1');
wrapperClass objWrap2= new wrapperClass(new Contact(LastName='Contact2'), 'Account2', 'Opp 2');


//serialize my objects
lstString.add(JSON.serialize(objWrap1));
lstString.add(JSON.serialize(objWrap2));
clsForAllFutureMethods.FirstFutureMethod(lstString);


---------------------------------------------------------------------------
We need to deserialize the JSON string as


public class clsForAllFutureMethods
{
  @future
  public static void FirstFutureMethod(List<String> lst)
  {
   List<wrapperClass> lstWrap=new List<wrapperClass>();
      for (String objWrap: lst)
     {

       lstWrap.add((wrapperClass) JSON.deserialize(ser, wrapperClass.class));
     }

  }
}

sObjects or Objects can’t be passed as an arguments to future methods


The reason why sObjects can’t be passed as arguments to future methods is because the sObject might change between the time you call the method and the time it executes.
 In this case, the future method will get the old sObject values and might overwrite them. 
 To work with sObjects that already exist in the database, pass the sObject ID instead (or collection of IDs) and use the ID to perform a query for the most up-to-date record. 

Lead convert fail when there is a process defined to update the lead during the conversion

If you have a process created for the Lead object in the process builder, you may encounter an error similar to the one below when trying to convert a lead.

"Error: System.DmlException: Update failed. First exception on row 0 with id XXXXXXXXXXXXXXX; first error: CANNOT_EXECUTE_FLOW_TRIGGER, The record couldn’t be saved because it failed to trigger a flow. A flow trigger failed to execute the flow with version ID XXXXXXXXXXXXX. Contact your administrator for help.: [] Class.leadconvert.BulkLeadConvert.updateLead: line 1375, column 1 Class.leadconvert.BulkLeadConvert.convertLead: line 151, column 1"

This will happen if the process you have created for leads is trying to update the lead when it's converted. When a lead is converted, some values on the lead are updated automatically and therefore, if the process is set to start "when a record is created or edited" and the criteria on is met, the process will try to update the lead after being converted, which is not possible. 

Converting Leads


The convertLead DML operation converts a lead into an account and contact, as well as (optionally) an opportunity.convertLead is available only as a method on the Database class; it is not available as a DML statement.
Converting leads involves the following basic steps:
  1. Your application determines the IDs of any lead(s) to be converted.
  2. Optionally, your application determines the IDs of any account(s) into which to merge the lead. Your application can use SOQL to search for accounts that match the lead name, as in the following example:
    1SELECT Id, Name FROM Account WHERE Name='CompanyNameOfLeadBeingMerged'
  3. Optionally, your application determines the IDs of the contact or contacts into which to merge the lead. The application can use SOQL to search for contacts that match the lead contact name, as in the following example:
    1SELECT Id, Name FROM Contact WHERE FirstName='FirstName' AND LastName='LastName' AND AccountId = '001...'
  4. Optionally, the application determines whether opportunities should be created from the leads.
  5. The application queries the LeadSource table to obtain all of the possible converted status options (SELECT ... FROM LeadStatus WHERE IsConverted='1'), and then selects a value for the converted status.
  6. The application calls convertLead.
  7. The application iterates through the returned result or results and examines each LeadConvertResult object to determine whether conversion succeeded for each lead.
  8. Optionally, when converting leads owned by a queue, the owner must be specified. This is because accounts and contacts cannot be owned by a queue. Even if you are specifying an existing account or contact, you must still specify an owner.

Example

This example shows how to use the Database.convertLead method to convert a lead. It inserts a new lead, creates a LeadConvert object and sets its status to converted, then passes it to the Database.convertLead method. Finally, it verifies that the conversion was successful.
01Lead myLead = new Lead(LastName = 'Fry', Company='Fry And Sons');
02insert myLead;
03
04Database.LeadConvert lc = new database.LeadConvert();
05lc.setLeadId(myLead.id);
06
07LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
08lc.setConvertedStatus(convertStatus.MasterLabel);
09
10Database.LeadConvertResult lcr = Database.convertLead(lc);
11System.assert(lcr.isSuccess());

Convert Leads Considerations

  • Field mappings: The system automatically maps standard lead fields to standard account, contact, and opportunity fields. For custom lead fields, your Salesforce administrator can specify how they map to custom account, contact, and opportunity fields. For more information about field mappings, see the Salesforce online help.
  • Merged fields: If data is merged into existing account and contact objects, only empty fields in the target object are overwritten—existing data (including IDs) are not overwritten. The only exception is if you specifysetOverwriteLeadSource on the LeadConvert object to true, in which case the LeadSource field in the target contact object is overwritten with the contents of the LeadSource field in the source LeadConvert object.
  • Record types: If the organization uses record types, the default record type of the new owner is assigned to records created during lead conversion. The default record type of the user converting the lead determines the lead source values available during conversion. If the desired lead source values are not available, add the values to the default record type of the user converting the lead. For more information about record types, see the Salesforce online help.
  • Picklist values: The system assigns the default picklist values for the account, contact, and opportunity when mapping any standard lead picklist fields that are blank. If your organization uses record types, blank values are replaced with the default picklist values of the new record owner.
  • Automatic feed subscriptions: When you convert a lead into a new account, contact, and opportunity, the lead owner is unsubscribed from the lead account. The lead owner, the owner of the generated records, and users that were subscribed to the lead aren’t automatically subscribed to the generated records, unless they have automatic subscriptions enabled in their Chatter feed settings. They must have automatic subscriptions enabled to see changes to the account, contact, and opportunity records in their news feed. To subscribe to records they create, users must enable the Automatically follow records that I create option in their personal settings. A user can subscribe to a record so that changes to the record display in the news feed on the user's home page. This is a useful way to stay up-to-date with changes to records in Salesforce.
-----------------------------------------------------------------------------------------

LeadConvert Arguments

This call accepts an array of LeadConvert objects (100 maximum). A LeadConvert object contains the following properties.
NameTypeDescription
accountIdIDID of the Account into which the lead will be merged. Required only when updating an existing account, including person accounts. If no accountID is specified, then the API creates a new account. To create a new account, the client application must be logged in with sufficient access rights. To merge a lead into an existing account, the client application must be logged in with read/write access to the specified account. The account name and other existing data are not overwritten. For information on IDs, see ID Field Type.
contactIdIDID of the Contact into which the lead will be merged (this contact must be associated with the specified accountId, and an accountId must be specified). Required only when updating an existing contact.
Important
If you are converting a lead into a person account, do not specify the contactId or an error will result. Specify only the accountId of the person account.
If no contactID is specified, then the API creates a new contact that is implicitly associated with the Account. To create a new contact, the client application must be logged in with sufficient access rights. To merge a lead into an existing contact, the client application must be logged in with read/write access to the specified contact. The contact name and other existing data are not overwritten (unlessoverwriteLeadSource is set to true, in which case only the LeadSource field is overwritten).
convertedStatusstringValid LeadStatus value for a converted lead. Required. To obtain the list of possible values, the client application queries the LeadStatus object. For example:
1SELECT Id, MasterLabel
2FROM LeadStatus WHERE IsConverted=true
doNotCreateOpportunitybooleanSpecifies whether to create an Opportunity during lead conversion (false, the default) or not (true). Set this flag to true only if you do not want to create an opportunity from the lead. An opportunity is created by default.
leadIdIDID of the Lead to convert. Required. For information on IDs, see ID Field Type.
opportunityNamestringName of the opportunity to create. If no name is specified, then this value defaults to the company name of the lead. The maximum length of this field is 80 characters. If doNotCreateOpportunity argument is true, then no Opportunity is created and this field must be left blank; otherwise, an error is returned.
overwriteLeadSourcebooleanSpecifies whether to overwrite the LeadSource field on the target Contact object with the contents of the LeadSource field in the source Lead object (true), or not (false, the default). To set this field to true, the client application must specify acontactId for the target contact.
ownerIdIDSpecifies the ID of the person to own any newly created account, contact, and opportunity. If the client application does not specify this value, then the owner of the new object will be the owner of the lead. Not applicable when merging with existing objects—if an ownerId is specified, the API does not overwrite the ownerIdfield in an existing account or contact. For information on IDs, see ID Field Type.
sendNotificationEmailbooleanSpecifies whether to send a notification email to the owner specified in theownerId (true) or not (false, the default).

Counters