New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

APEX

89 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. Covering Code for CompareTo method in Apex:
    use stmt like : value1.compareTo(value2);//It will cover.

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

    ReplyDelete
  32. 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
  33. 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
  34. 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
  35. add all rows in soql query will return perminantly deleted records also.

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

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

    ReplyDelete
  38. 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
  39. When calling the static method constructor won't be invoked.

    ReplyDelete
  40. 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
  41. Use trigger.isexecuting in any class to get to know the code is executing from apex trigger or not.

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

    ReplyDelete
  43. 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
  44. /* 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
  45. Query from ApexClass to fetch all the apex classes.
    Query from ApexTrigger to fetch all the apex triggers.

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

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

    ReplyDelete
  48. 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
  49. 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
  50. We can convert maximum 100 leads at a time using database.convertLead();

    ReplyDelete
  51. 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
  52. To fetch the first three characters of the object -
    -----------------------------------------------------------------------
    String oppKeyPrefix = Opportunity.sObjectType.getDescribe().
    getKeyPrefix();

    ReplyDelete
  53. 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
  54. 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
  55. For the schema.describe result map keys are Case-Insensitive.

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

    ReplyDelete
  57. 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
  58. Modifying records while running the batch job salesforce.

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

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

    ReplyDelete
  61. 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
  62. 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
  63. After inserting the record to access the 'AutoNumbr' field value we should query from the database.

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

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

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

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

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

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

    ReplyDelete
  70. 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
  71. After inserting a case, one of the child case should be created for after insert event?
    Recursive triggers will occur.

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

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

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

    ReplyDelete
  75. To know the total count of an object if there are more than 50000 records in an object -
    public class Test_Aggregate{
    public static void TestAgg() {
    Integer intCount = 0;

    for(AggregateResult result :[SELECT COUNT(Id) intVal FROM Custom_Object__c])
    {
    intCount+=(Integer)result.get('intVal');
    }

    System.debug('No of records are: '+intCount);
    }
    }
    Reference:
    https://salesforce.stackexchange.com/questions/130013/how-to-get-exact-record-count-for-an-object-using-soql-for-more-than-1-million-r

    ReplyDelete
  76. Working in Multi-Currency Org -
    SELECT Amount, FORMAT(amount) Amt, convertCurrency(amount) convertedAmount,FORMAT(convertCurrency(amount)) convertedCurrency FROM Opportunity WHERE Amount > USD5000

    convertCurrency(amount) --> converting currency to the user locale
    FORMAT(convertCurrency(amount)) --> formating to add the currency symbol in output
    USD5000 --> currency symbol+amout which will be used in where clause.

    ReplyDelete
  77. DataType name: getType().Name()

    ReplyDelete
  78. Git Flow -
    http://nvie.com/posts/a-successful-git-branching-model/#decentralized-but-centralized

    ReplyDelete
  79. Password reset email while creating new user in apex -
    Database.DMLOptions dmlo = new Database.DMLOptions();
    dmlo.EmailHeader.triggerUserEmail = true;
    usr.setOptions(dmlo);

    ReplyDelete
  80. Trigger Scenario -
    https://gist.github.com/sriniind19/c394ecfe6a47e8a88fe7f0488e5d238c

    ReplyDelete
  81. While While creating the portal user in apex it is giving error saying the 'account owner should have the role'
    Resolution:
    if(account.owner.UseRoleName) {
    //Create portal user
    }
    //Note: make sure to give the role for the contact's parent account's owner.

    ReplyDelete
  82. ***************
    To match the current datetime with the SOQL query datetime formatGMT
    ***************
    Approach - 1
    ------------
    DateTime dt = datetime.now();
    Datetime tody = Datetime.newInstanceGmt(dt.year(), dt.month(), dt.day(), dt.hour(), dt.minute(), dt.second());
    system.debug(tody.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ'));

    Approach - 2
    Datetime now = Datetime.now();
    Integer offset = UserInfo.getTimezone().getOffset(now);
    Datetime local = now.addSeconds(offset/1000);
    system.debug(local.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ'));

    *******************

    ReplyDelete
  83. onBeforeInsert() {
    //Multiple methods are called for each requirement,
    //Due to this, it is hitting number of soql query limits.
    //It is better to know about the apex design patterns.
    }

    ReplyDelete
  84. Mac VS Code Path: /Library/Java/JavaVirtualMachines/jdk-11.0.8.jdk/Contents/Home

    ReplyDelete
  85. Account Share Record -
    AccountShare accShare = new AccountShare(
    AccountAccessLevel = 'Edit',
    AccountId = event.WhatId,
    UserOrGroupId = event.OwnerId,
    OpportunityAccessLevel = 'Edit'
    );

    ReplyDelete

Labels