Posts

Showing posts from 2023

Share the file to external User

 Requirement:  Once the file is uploaded by the internal user then it will be shared the external user (Portal User) Solution Write a trigger on the contentDocumentLink object once the file uploaded share the file to the external user public without sharing class ContentDocumentLinkTriggerHandler {         public static final String ALL_USERS_SHARING = 'AllUsers'; public void runTrigger(){ // Method will be called to handle After Insert ContentDocumentLink if(Trigger.isAfter && Trigger.isInsert) { onAfterInsert((list<ContentDocumentLink>)trigger.new,(map<id,ContentDocumentLink>) trigger.newMap); } // Method will be called to handle After Update ContentDocumentLink if(Trigger.isAfter && Trigger.isUpdate) { onAfterUpdate((list<ContentDocumentLink>)trigger.new,(map<id,ContentDocumentLink>) trigger.newMap); } // Method will be called to handle After Update ContentDocumentLink if(Trigger.isAfter &am

Get the record Count of all countable Sobjects in Salesforce

Image
  Salesforce: Get the record count of all objects Use case: A client wants to access the data volume for data migration and needs to get record counts from all countable objects in Salesforce Solution:  1) log in to Workbench 2) Go to Utilities > Rest Explorer 3) Do a GET call on this URI: /services/data/v56.0/limits/recordCount ( change 56.0 with the latest API version) 4) Check the result. Copy the JSON and convert it to CSV Note: 1) The Rest call result does not include uncountable objects and record count for deleted records in the recycle bin 2) Ensure your user has "View Setup and Configuration” permission

Show Hyperlink against the Record in Datatable in LWC

Image
  Requirements : Show the case records in the data table. when click on case number it will redirect to the detail page Apex Class: showCaseRecordsinDatatable public with sharing class showCaseRecordsinDatatable {        @AuraEnabled     public static list<case> fetchCases(){         try {             return [Select Id, subject,CaseNumber, Description, AccountID, Account.Name,ContactID, contact.Name,Status, priority from case];                    } catch (Exception e) {             throw new AuraHandledException(e.getMessage());         }     } } --------Create LWC------- <template>     <lightning-card  variant="Narrow"  title="Case List" icon-name="standard:case">         <div class="slds-m-around_small">             <lightning-datatable                 key-field="id"                 data={result}                 show-row-number-column                 hide-checkbox-column                 columns={columnsList}

Get Record based on Specific Date in SOQL using IN Operator

 We can use IN operator to put a filter on multiple dates while using the Day_Only function. Get specific date of records using IN operator with Day_Only Function  List<Account> lstofacc = [SELECT Id, Name, CreatedDate FROM Account WHERE Day_Only(CreatedDate) IN (2022-01-24, 2022-01-25)]; System.debug(accList); bind variables as well: Date d1 = Date.parse('01/24/2022'); Date d2 = Date.parse('01/25/2022'); List<Account> accList = [SELECT Id, Name, CreatedDate FROM Account WHERE Day_Only(CreatedDate) IN (:d1, :d2)]; System.debug(accList);

Get my org’s url using Salesforce Formula field (Text Type)

  Get my org’s url: The $Api.Partner_Server_URL_530 variable returns the endpoint of your Salesforce org. This formula is saying “Starting from the left of the entire URL, return the characters all the way until the position of “/services”. LEFT({!$Api.Partner_Server_URL_530},FIND("/services", {!$Api.Partner_Server_URL_530}))

number of Saturdays between those 2 dates. Create formula field

FLOOR(( End_Date__c -  Start_Date__c )/7) + IF(OR (WEEKDAY(Start_Date__c )=7, WEEKDAY(End_Date__c )=7, WEEKDAY(Start_Date__c )>WEEKDAY(End_Date__c )),1,0) If you want the number of Sundays: FLOOR(( End_Date__c -  Start_Date__c )/7) + IF(OR (WEEKDAY(Start_Date__c )=1, WEEKDAY(End_Date__c )=1, WEEKDAY(Start_Date__c )>WEEKDAY(End_Date__c )),1,0) This is easily changed for any day of the week. You only need to change the "WEEKDAY" number (1 for Sunday, 2 for Monday, 3 for Tuesday, etc) in this part: WEEKDAY(Start_Date__c )=1, WEEKDAY(End_Date__c )=1

What is Saml and Oauth and Authentication flow in salesforce

Difference between SAML and OAuth Overview of SAML 1. The user makes a request to Force.com for a specific resource. 2. Force.com detects the user needs to authenticate and redirects the user to their SAML Identity Provider. 3. The user accesses their IdP and authenticates. 4. Once authenticated, the IDP sends a SAML Response back to Salesforce.com. 5. Force.com processes the SAML assertion and logs the user in. Overview of OAuth 1. The OAuth Client makes an authorization request. 2. The Authorization Server authenticates the user. 3. The user authorizes the application. 4. The application is issued an OAuth token. Difference between Web server OAuth flow, User agent flow OAuth Authentication flow and Username-Password OAuth Authentication flow Web server OAuth flow  Typically used for web applications where server-side code needs to interact with Force.com APIs on the user’s behalf, for example DocuSign. Trust that the web server is secure to protect the consumer secret. Client applic

Dynamic SOQL based on Sobject Name and Where Clause

 public class DynamicSOQLUtil {     // Returns a dynamic SOQL statement for the whole object, based on object name and where clause as a dynamic     public static string getCreatableDynamicFieldsSOQL(String objectName, String whereClause){                  String selects = '';         // Check whereclause if null then return null         if (whereClause == null || whereClause == ''){ return null; }                  // Get a map of field name and sobject field         Map<String, Schema.SObjectField> objFieldMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();         list<string> selectFields = new list<string>();                  if (objFieldMap != null){             for (Schema.SObjectField objFt : objFieldMap.values()){ // loop through all field tokens                 Schema.DescribeFieldResult fd = objFt.getDescribe(); //field describe  for each field                //if (fd.isCreateable()){ // if needed onl

Get fields in SOQL from FIeldSet

global class BatchclassName implements Database.Batchable<sObject>, Database.Stateful, Database.AllowsCallouts{       global Database.QueryLocator start(Database.BatchableContext bc) {         return gAllRecords();     public Database.QueryLocator gAllRecords(){      try{ //Create fieldset on Object and get fields in SOQL query, BankFieldSet this fieldset name on bank object String queryString = 'Select Id'; for(Schema.FieldSetMember fieldMember : sObjectType.Bank__c.FieldSets.BankFieldSet.getFields()){ queryString += ', '+fieldMember.getFieldPath();} system.debug('queryString@@@'+queryString); queryString+=' FROM Bank__c WHERE isActive__c =true AND Location__c=\'Noida\' AND IsNeeded__c= true AND Status__c IN (\'Failed\',\'Unsuceess\') LIMIT '+Integer.valueOf(Label.LabelName); return Database.getQueryLocator(queryString); }catch(Exception ex){ ErrorLog__c log = new ErrorLog__c(); log.Message

In Schedule class run next job from configuration level

global class Schedularclassname implements Schedulable {   global void execute(SchedulableContext SC) {        List<AsyncApexJob> jobs = new List<AsyncApexJob>(); Id thisClassId = [SELECT Id, Name FROM ApexClass WHERE name = 'BatchClassName' LIMIT 1].Id; //Setup Custom Setting Schedular_Settings__c store the time and no of record process in batach class  //Scheduled_Time__c  store time when next batch will run //Schedular_Records__c add batch size how many record will process Schedular_Settings__c objschedule = Schedular_Settings__c.getInstance('Schedular'); if(objschedule!=null && objschedule.Scheduled_Time__c != null && objschedule.Schedular_Records__c != null){ jobs = [select id from AsyncApexJob where (status = 'Processing' OR status = 'Holding' OR status = 'Queued' OR status = 'Preparing') AND ApexClassId = :thisClassId AND JobType = 'BatchApex']; if(jobs == null  || jobs.size()

Get Last day of Month

Get Last day of a month (28, 29, 30 or 31)? Formula DAY(ADDMONTHS(DATE(YEAR(DateField__c), MONTH(DateField__c),1),1)-1) The trick here is to take the 1st of the month and year of the date field, add 1 month to it and subtract 1 day. For example, if my date field is March 3rd 2022, the formula will add 1 month to March 1st 2022 and will return April 1st 2022. We then subtract 1 day to get March 31st 2022.

Generate Random String

 DateTime currentDate = DateTime.now(); String randstring = currentDate.format('ddMMHHmmss'); Integer randomNumberToAppend = null; while(true){     randomNumberToAppend = Integer.valueOf(Math.random()*10000);     if(String.valueOf(randomNumberToAppend).length()==4){         break;     } } randstring += randomNumberToAppend; System.debug('randstring@@@'+randstring);

WAT if the owner of an account is changed then the owner of the related contacts should also be updated.

 Account Trigger ============================================ trigger AccountTrigger on Account (after update) {   Set<ID> accountId = new Set<ID>();   if(Trigger.IsAfter && Trigger.IsUpdate){     for(Account objAcc : trigger.new){       if(trigger.oldMap.containsKey(objAcc.id)){         if(trigger.oldMap.get(objAcc.id).OwnerId != objAcc.OwnerId){           accountId.add(objAcc.Id);         }       }     }     if(accountId != null && accountId.size() > 0 ){       AccountTriggerHandler.UpdateOwnerofContact(Trigger.newMap, accountId);     }   } } ============================================ AccountTriggerHandler Class public with sharing class AccountTriggerHandler {   public static void UpdateOwnerofContact(Map<Id,Account>accountMap,Set<id>accountId){     List<Contact> lstUpdateOwnerofContact = new List<Contact>();     Map<id,Contact> mapofIdToContact = new Map<id,Contact>([SELECT Id,Name,AccountId From contact WHERE Acc

Get Interface Class List from SOQL

ApexTypeImplementor Object: Get the list of all classes which implement a particular interface with the help of ApexTypeImplementor object. List<ApexTypeImplementor> lstofbatchclass =[SELECT Id,ClassName FROM ApexTypeImplementor WHERE InterfaceName = 'Batchable']; https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_apextypeimplementor.htm