APEX

80 comments:

  1. Constants can be defined using the final keyword, which means that the variable can be assigned at most once, either in the declaration itself, or with a static initializer method if the constant is defined in a class. For example:

    public class myCls {
    static final Integer PRIVATE_INT_CONST;
    static final Integer PRIVATE_INT_CONST2 = 200;

    public static Integer calculate() {
    return 2 + 7;
    }

    static {
    PRIVATE_INT_CONST = calculate();
    }
    }

    ReplyDelete
  2. Steps to reduce the code:
    -------------------------
    http://developer.force.com/cookbook/category/apex/recent

    ReplyDelete
  3. To eliminate duplicates within sObject use set,
    To eliminate duplicates to insert which another object already have two for loops comparision

    ReplyDelete
  4. To put the logic of a trigger in a class and calling the class from the trigger:

    http://blog.jeffdouglas.com/2011/08/23/salesforce-trigger-when-rollups-summaries-not-possible/

    ReplyDelete
  5. Use of @IsTest(SeeAllData = True):
    ------------------------------------
    test methods don’t have access by default to pre-existing data in the organization.
    To provide access to that data (From API 24.0 Version) We should use above method.

    ReplyDelete
  6. Test Class for Batch Class:
    ----------------------------
    @isTest
    private class TestBatchClass{
    static testMethod void testBatchClass() {
    BatchClass bc = new BatchClass();
    bc.query = 'Select Id From Account Limit 200';

    Test.startTest();
    Database.executeBatch(bc, 200);
    Test.stopTest();
    }
    }

    ReplyDelete
  7. Batch Class:
    Up to five queued or active batch jobs are allowed for Apex

    ReplyDelete
  8. Sample__c s = new Sample__c();
    insert s;
    insert s;


    nothing will insert

    ReplyDelete
  9. To check the current user in permission set:
    List psusers = [SELECT Id, AssigneeId FROM PermissionSetAssignment WHERE PermissionSet.Name = 'PermissionSetName' AND AssigneeId =:Userinfo.getUserId()];

    ReplyDelete
  10. Naming Conventions:
    http://salesforce.stackexchange.com/questions/890/what-is-a-good-set-of-naming-conventions-to-use-when-developing-on-the-force-com

    ReplyDelete
  11. Creating RollUp Summary Fields:
    https://github.com/abhinavguptas/Salesforce-Lookup-Rollup-Summaries

    ReplyDelete
  12. Could not run tests on class [ID]:
    http://boards.developerforce.com/t5/Apex-Code-Development/Running-testMethods-Could-not-run-tests-on-class-ID/m-p/681261#M126770

    ReplyDelete
  13. Business Hours Math:
    https://github.com/redargyle/BusinessHoursMath

    ReplyDelete
  14. Using Business Hours:
    Datetime starttime = Datetime.now(); Datetime nexttime = BusinessHours.add(record.id,startTime,1000L);

    ReplyDelete
  15. To get week ends between a date range:
    http://www.cloudsuccess.com/blog/apex-function-to-calcuate-weekdays/

    ReplyDelete
  16. Set.containsKey('xyz') allows cases as different won't work for duplicates
    It allows xYZ or XYZ or Xyz as different values

    ReplyDelete
  17. String.equalsIgnoreCase(String) to avoid case sensitive

    ReplyDelete
  18. prepopulating to populate look up give the name of the parent object to pass the id of the parent object use target object look up field id which should be appended with _lkid.

    ReplyDelete
  19. Query queue name in salesforce:
    https://success.salesforce.com/answers?id=90630000000gsFWAAY

    ReplyDelete
  20. Insert Queue Records in SFDC:
    1. insert records into Group object (name, type).
    2. Export above inserted records (Id's of above inserted records.)
    3.Prepare data with id, type (queue type) and insert into QueueSobject
    Reference: http://salesforcedeveloperblog.blogspot.com/2012/05/queue-not-associated-with-sobject-type.html

    ReplyDelete
  21. On before insert no Trigger.newMap since new record id's won't be available and trigger.new will be available

    ReplyDelete
  22. Salesforce SOQL Query:
    http://simplysfdc.blogspot.in/2013/09/salesforce-soql-query.html

    ReplyDelete
  23. Making Rejection Comments Mandatory:
    http://christopheralunlewis.blogspot.com/2012/09/making-rejection-comments-mandatory-in.html

    ReplyDelete
  24. Cannot modify trigger.new in after update.

    ReplyDelete
  25. Profile Codes if we use $Profile.Name Value:
    System Administrator PT1
    Standard User PT2
    ---- -
    Customer Portal Manager PT14

    ReplyDelete
  26. S

    for(int i=1;i<=100;i++)
    {
    if(i%10==0)
    continue;
    Sysm.out.println(i);
    }

    ReplyDelete
  27. Abstract Class Name: MyAbstractClass
    How to cover the code for Abstract Class?
    Need to write a mock class like below -
    public class MyAbstractClassMockClass extends TriggerHandler {
    public MyAbstractClassMockClass () {
    }
    }
    Write a Test Class like below -
    @isTest
    private class TestMyAbstractClass {
    static testMethod void myUnitTest() {
    MyAbstractClassMockClass mbc = new MyAbstractClassMockClass();
    mbc.method1();//which is declared in MyAbstractClass
    //Repeat the same for all the methods.
    }
    }

    ReplyDelete
  28. To generate unique token in Apex saelsforce:
    DateTime now = System.now();
    String formattednow = now.formatGmt('yyyy-MM-dd')+'T'+ now.formatGmt('HH:mm:ss')+'.'+now.formatGMT('SSS')+'Z';
    Blob bsig = Crypto.generateDigest('MD5', Blob.valueOf(formattednow ));
    String token = EncodingUtil.base64Encode(bsig);
    if(token.length() > 255) { token = token.substring(0,254); }
    secureToken = Encodingutil.urlEncode(token, 'UTF-8').replaceAll('%','_');

    return secureToken;

    ReplyDelete
  29. Apex Trigger Framework:
    https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices

    ReplyDelete
  30. Online Code Editor for salesforce:
    https://www.aside.io/

    ReplyDelete
  31. Covering Code for CompareTo method in Apex:
    use stmt like : value1.compareTo(value2);//It will cover.

    ReplyDelete
  32. hierarchy customsettings or list customsettings won't work without 'seeAllData' in Test Classes.

    ReplyDelete
  33. trigger UserTrigger on Account(before insert) {
    }
    For the above trigger error is coming as mentioned below:
    Error: Compile Error: Incorrect SObject type: Account should be User at line 1 column 1
    What would be the reason?
    He is creating the trigger from the user object.

    ReplyDelete
  34. Excluding weekdays and holidays in apex:
    public void populateExcludingholidaysandweekends() {
    List holidaylst = [Select h.ActivityDate, h.Name, h.IsRecurrence From Holiday h];
    Integer totalholidays = 0;
    for(Holiday h : holidaylst) {
    if(h.ActivityDate >= tor.Start_Date__c && h.ActivityDate <= tor.End_Date__c ) {
    totalholidays += 1;
    }
    }
    Integer i = 0;
    Datetime sdate = Datetime.newInstance(tor.Start_Date__c, Time.newInstance(12, 0, 0, 0));
    Datetime edate = Datetime.newInstance(tor.end_Date__c, Time.newInstance(12, 0, 0, 0));
    Integer totalnumberDays = tor.Start_Date__c.daysBetween(tor.end_Date__c) + 1;
    while (sdate <= edate) {
    if (sdate.format('E') == 'Sat' | sdate.format('E') == 'Sun'){
    i = i + 1;
    }
    sdate = sdate.addDays(1);
    }
    if(totalholidays != null)
    i += totalholidays;
    Integer workingdays = (totalnumberDays - i);
    if(!usr.Non_Exempt_Employee__c)
    tor.Total_Hours_Requested__c = workingdays;
    else
    tor.Total_Hours_Requested__c = (workingdays * 8);
    }

    ReplyDelete
  35. Deleting child records if we delete the parent record in case of look-up relationship -
    trigger ProjectTrigger on Proj__c (before delete) {
    List empDelLst = [select id, Project_Latest__c from Employee__c where Project_Latest__c in: trigger.oldMap.keyset()];
    delete empDelLst;
    }

    ReplyDelete
  36. add all rows in soql query will return perminantly deleted records also.

    ReplyDelete
  37. Fetching RecordTypeId using Dynamic Apex:
    Schema.DescribeSObjectResult resSchema = Case.sObjectType.getDescribe();
    Map recordTypeInfo = resSchema.getRecordTypeInfosByName();
    Id recTypeId = recordTypeInfo.get('Record Type Name').getRecordTypeId();

    ReplyDelete
  38. Creating Test Data PROGRAMMATICALLY:
    http://startupsandcrm.com/2013/08/01/dynamic-visualforce-object-permissions-and-sobject-describe-results/

    ReplyDelete
  39. Checking whether the day is a business day or not:
    --------------------------------------------------
    BusinessHours bushours = [select id from Businesshours where isDefault = true and Name='Default' limit 1];
    Date outputDate = (BusinessHours.add(bushours.id, Datetime.newInstance(inputDate,Time.newInstance(12, 0, 0, 0)), 1000L)).date();
    Note: if inputDate and outputDate both are not equal then it is a holiday.

    ReplyDelete
  40. When calling the static method constructor won't be invoked.

    ReplyDelete
  41. Setting java developer environment for salesforce:
    https://help.salesforce.com/help/pdfs/en/salesforce_developer_environment_tipsheet.pdf

    ReplyDelete
  42. java -classpath c:\tools.jar;c:\wsc-22.jar com.sforce.ws.tools.wsdlc c:\Enterprise.wsdl c:\stub.jar

    Follow the syntax like above to generate the jar file from Enterprise WSDL

    ReplyDelete
    Replies
    1. To generate the jar file we should have jdk(to write code) ,
      Note: jre(executing java)

      Delete
    2. Useful site for WSC files:
      http://code.google.com/p/sfdc-wsc/downloads/list

      Delete
    3. Use partnerWSDL and your service which is generated from the soap exposed class.

      Delete
  43. Use trigger.isexecuting in any class to get to know the code is executing from apex trigger or not.

    ReplyDelete
  44. For Queried records we cannot use addError method in triggers.

    ReplyDelete
  45. How to get combination of Two fields unique…… ?
    Ex: whenever we want combination of two fields must not be same
    ie. If we have Standard Account object in this 1.Acccount Name 2.Billing country
    Combination of these two fields should be unique.
    This can be achieved By Work Flow Rule….
    1. We need to Create a Text Formula field And make it Unique.
    2.Now Create a Work Flow Rule On Account Object.
    (1. In This The Evaluation Criteria: Created anytime time edited to meet the Criteria.
    2. Rule Criteria
    (Account: Account Name NOT EQUAL TO null) AND (Account: Billing Country NOT EQUAL TO null)
    3. Now the Work Flow Action is Updating the Unique field ( In This The formula is combining two fields Account Name And Billing country)

    ReplyDelete
  46. /* Description:
    * ============
    * Controller Class for VF Page - PageA
    * Purpose of the class
    *
    * Author:
    * ========
    * User A
    *
    * Revision History:
    * ========
    * 01/31/YYYY - Initial development built
    *
    * Modified By
    * ===========
    * User B
    *
    * Revision History:
    * ========
    * 06/29/YYYY - Modified as part of latest release.
    */

    ReplyDelete
  47. Query from ApexClass to fetch all the apex classes.
    Query from ApexTrigger to fetch all the apex triggers.

    ReplyDelete
  48. Triggering DML Exception for Code Coverage:
    http://salesforce.stackexchange.com/questions/9888/triggering-a-dml-exception-for-test-coverage

    ReplyDelete
  49. To get the GMT time use Date.newInstanceGMT() method which will bypass the user's current logged in time zone.

    ReplyDelete
  50. Converting date for the CreatedDate:
    DateTime dt = date.today();
    Datetime tody = Datetime.newInstanceGmt(dt.year(), dt.month(), dt.day(), 0, 0, 0);
    system.debug('@@@'+tody);

    ReplyDelete
  51. Test Class -
    Error: System.VisualforceException: Modified rows exist in the records collection!
    Cause: When covering standardSetController due to the stmt setPageSize(), it is causing this error.
    Solution: in test class while creating object keep that in try and catch block.

    ReplyDelete
  52. We can convert maximum 100 leads at a time using database.convertLead();

    ReplyDelete
  53. One future method to other future method invocation will happen due to some new enhancements to avoid these kind of scenarios imeplement like below -

    public class InvokeClass {
    if(system.future())
    UtilityClass.syncMethod(some parameters);
    else
    UtilityClass.asyncMethod(some parameters);
    }

    public class UtilityClass {
    //Invoke if request comes from a non-future method.
    @future
    public static asyncMethod(some parameters) {
    }

    //Invokes if request comes from a future method.
    public static syncMethod(some parameters) {
    }
    }

    ReplyDelete
  54. To fetch the first three characters of the object -
    -----------------------------------------------------------------------
    String oppKeyPrefix = Opportunity.sObjectType.getDescribe().
    getKeyPrefix();

    ReplyDelete
  55. Avoiding duplicates while querying from the database:
    1. create a custom text field and make it as unique and update the field with workflow field update.
    2. Use a before trigger (query the records with the names of trigger.new) Note; don't query all the records.
    Note: after before trigger workflow rules fire (in between after triggers, assignment and auto responsive rules will fire).

    Doing upsert operation with 5 records (3 are new records, 2 records will update), how many times trigger fire?
    1. Trigger fires two times.
    Note: If consider that it fire only one time trigger.new hold 3 records, trigger.old hold 5 records (always trigger.new count and trigger.old count both are same).

    ReplyDelete
  56. Based on Parent object city all the child's which are having that city should be linked -
    trigger DepartmentTrigger on Department__c (after insert,after update) {
    Set citySet = new Set();
    for(Department__c dep : trigger.new) {
    citySet.add(dep.Location__c);
    }
    Map> cityEmpMap = new Map>();
    for(Employee__c emp : [select city__c,department__c from Employee__c where city__c in: citySet]) {
    if(cityEmpMap.containsKey(emp.city__c)) {
    cityEmpMap.get(emp.city__c).add(emp);
    }
    else {
    cityEmpMap.put(emp.City__c,new List{emp});
    }
    }
    system.debug('cityEmpMap'+cityEmpMap);
    //Triggering Logic
    List empUpdLst = new List();
    for(Department__c dep : trigger.new) {
    if(cityEmpMap.containsKey(dep.Location__c)) {
    for(Employee__c emp :cityEmpMap.get(dep.Location__c)) {
    emp.department__c = dep.id;
    empUpdLst.add(emp);
    }
    }
    }
    if(empUpdLst.size() > 0) {
    update empUpdLst;
    }
    }

    ReplyDelete
  57. For the schema.describe result map keys are Case-Insensitive.

    ReplyDelete
  58. Based on the Id update the records instead of querying from the database.

    ReplyDelete
  59. Max. batch size if the return type is Database.quryLocator: 2000
    Max. batch size if the return type is iterable: no upper limit but other governor limit like heap size will might hit if we give more batch size.

    ReplyDelete
  60. Modifying records while running the batch job salesforce.

    ReplyDelete
  61. Lightning:
    https://developer.salesforce.com/blogs/developer-relations/2015/02/lightning-components-sample-app-belgian-beer.html

    ReplyDelete
  62. To split with the pipe symbol -
    -------------------------------
    stringname.split('\\|')

    ReplyDelete
  63. Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Record Type ID: this ID value isn't valid for the user: : [RecordTypeId]

    Resolution -
    1. check if the recordid is null.
    2. In test class plese set the current page on the top of the testMethod.

    ReplyDelete
  64. Apex Managed Sharing Considerations -
    1. In Share Object, for each record one entry will be maintained with Rowcause as 'Owner'.
    2. Programmatically while sharing the records if you don't mention the Rowcause then it will default rowcause to 'Manual'
    3. While deleting the records programmatically from the share object in filter condition keep it as 'Manual' (should be other than owner).
    4. Otherwise following kind of error will come -
    first error: DELETE_FAILED, cannot delete owner or rule share rows, share rows salesforce

    ReplyDelete
  65. After inserting the record to access the 'AutoNumbr' field value we should query from the database.

    ReplyDelete
  66. Chrome Extensions -
    1. RestClient.html
    2. Salesforce Code Advanced Searcher

    ReplyDelete
  67. https://chrome.google.com/webstore/detail/salesforce-advanced-code/lnkgcmpjkkkeffambkllliefdpjdklmi?hl=en

    ReplyDelete
  68. Capturing the email status -
    Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    ReplyDelete
  69. Queueable Apex - with no governor limits enforced for the future operations.

    ReplyDelete
  70. Network Issue -
    If the Community is not present the if we try to use 'Network', It will throw the compilation error.

    ReplyDelete
  71. Yesterday and today functions are not working for SOQL queries in eclipse where as directly in browser it is working out.

    ReplyDelete
  72. SOSL/SOQL present in a account trigger, if the account records are inserted using 150 different DML stmts,
    these triggers also fire multiple times and every time trigger.new will be 1 in size, if more than 20 records are inserted then
    21 SOSL limits will be reached.

    If more than 100 times DML stmt executes then 101 SOQL limits will be reached.

    ReplyDelete
  73. After inserting a case, one of the child case should be created for after insert event?
    Recursive triggers will occur.

    ReplyDelete
  74. Emails in Apex Code -
    We cannot send email by calling a method from constructor. (from constructors we cannot send emails )

    ReplyDelete
  75. Database.Batchable --> Database is a namespace not the Class, inside the classes we cannot keep the interface.

    ReplyDelete
  76. Describing object (dynamic apex) -
    Schema.getGlobalDescribe().get(objectApi).getDescribe().fields.getMap().get(fieldApi).getDescribe().getReferenceTo()[0].getDescribe().getName();

    ReplyDelete

Labels