Posts

Roll up Amount from Child Object To Parent Object in Case of Lookup Relationship

Case : Roll up the values from Child to Parent Object in Case of Lookup Relationship. On Child Object (ChildObjectApiName__c) there is custom field Amount__c On Parent Object(ParentObjectApiName__c) there is a custom Field TotalChildAmount__c On Child Object relation ship of Parent Object is ParentObjectRealtionShipApiName__c Trigger triggerName on ChildObjectApiName__c(aftet insert, after delete, after update, after undelete) { set<id> setofParentObjectID = new set<id>(); // Storing the parent object Ids map<Id, ParentObjectApiName__c> mapofParentObjectIdToParnetObject  = new Map<Id, ParentObjectApiName__c>(); // Map is used for Storing the Parent Record Id to Parent Object if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) { for(ChildObjectApiName__c objChildObject1: trigger.new) { if(objChildObject1.ParentObjectRealtionShipApiName__c != null) { setofParentObjectID.add(objChildObject1.ParentObjectRealtion...

How to Select All Fields with SOQL in Apex

How to Select All Fields with SOQL in Apex // Based on Record ID , fetch all the field particular object ID recordId = '01t90000000vQFw'; DescribeSObjectResult describeResult = recordId.getSObjectType().getDescribe(); List<String> fieldNames = new List<String>( describeResult.fields.getMap().keySet() ); System.debug( fieldNames); String query = ' SELECT ' + String.join( fieldNames, ',' ) +' FROM ' + describeResult.getName() +' WHERE ' +     ' id = :recordId ' + ' LIMIT 1 ';        // return generic list of sobjects or typecast to expected type List<SObject> records = Database.query( query ); System.debug( records ); // Based on Object without an ID, simply specify the object to then derive the sobject type     DescribeSObjectResult describeResult = SobjectApiName.getSObjectType().getDescribe(); List<String> fieldNames = new List<String>( describeResult.fields.getMap().key...

Show Pagination and Colum Sorting on VF page using Jquery Plugin

Image
Requirement:  To show Account record in table form on VF page and user able to paginate pages and sort the column: Solution:  Using Jquery Plugin you can directly implement pagination and column Sorting Download Jquery Plugin : https://sfcomponent-dev-ed.my.salesforce.com/sfc/p/#6F000001f5y8/a/6F0000004XWj/F0czOc51PF5iaC7ERZBb.cO.nU95xWyEaGcUTmPkCaU Add data table zip file in Static Resource Class Code: public class AccountController {  public List<Account> lstofacc{get;Set;}  public AccountController ()  {      lstofacc = new List<Account>([select id,AccountNo, name from account]);        } } Page Code: <apex:page controller=" AccountController  " sidebar="false" standardStylesheets="false" docType="html-5.0" tabStyle="Account"> <head> <apex:stylesheet value="{!URLFOR($Resource.DataTable,'DataTable/datatables.min.css')}" /> <apex:stylesheet value=...

Update Account Comment from Task Insertion Using Trigger

Requirement: Write a trigger to update account comment field from Task comment value on insertion of Task under Account Solution : trigger updateAccountCommentFromTask on Task (before insert) { String account_prefix = Schema.SObjectType.Account.getKeyPrefix(); Map<Id,Account> accountMap = new Map<Id,Account>(); Set<id> setofWhatID = new Set<id>(); for (Task objTask: Trigger.new)  { setofWhatID.add(objTask.WhatId); } Map<id,Account> MapAccIDToAccount = new Map<id,Account>([Select Id, Account_Status_Sales__c from Account Where Id in :setofWhatID]); for (Task objTask: Trigger.new) if(objTask.Subject != null && objTask.WhatId !=null && ((String)objTask.WhatId).startsWith(account_prefix)) { Account a = MapAccIDToAccount.get(objTask.WhatId); a.Comment__C = objTask.Comment__c; accountMap.put(a.id,a); } try { update accountMap.values(); } catch (system.Dmlexception e)  { sy...

Duplicate Prevent Lead Based On Email

Requirement : Write a trigger to prevent duplicate Email on Lead Object Solution : trigger leadDuplicatePreventer on Lead (before insert, before update) { Map<String, Lead> leadMap = new Map<String, Lead>(); for (Lead lead : System.Trigger.new) { if ((lead.Email != null) &&     (System.Trigger.isInsert || (lead.Email != System.Trigger.oldMap.get(lead.Id).Email))) { if (leadMap.containsKey(lead.Email)) {   lead.Email.addError('Another new lead has the ' + 'same email address.'); } else {      leadMap.put(lead.Email, lead);  } } } for (Lead lead : [SELECT Email FROM Lead WHERE Email IN :leadMap.KeySet()]) { Lead newLead = leadMap.get(lead.Email); newLead.Email.addError('A lead with this email ' + 'address already exists.'); } }                              Thanks,               ...

Save the Batch Error Job ID in Custom Object in case of Failure

Requirement :  Get the Failure record when processing thru batch Class Solution : Create a custom object for saving batch log errors and create a batch class   Custom Object: Batch_Log_Error__c  Custom Fields : Job_id__c,Record_Id__c,Error__c global class BatchClassName implements Database.batchable<sObject>,Schedulable{ String query ; // define Constructor global BatchClassName(){  query = 'Select id from SobjectapiName'; }  // Start Method Call    global Database.QueryLocator start(Database.BatchableContext BC){         return Database.getQueryLocator(query);    }        //  Execute Method Call global void execute(Database.BatchableContext bc, List<SobjectapiName> scope){ // Declare SobjectList and BatchErrorLoglst  list<SobjectapiName> lstofsobject  = new list<SobjectapiName>(); list<Batch_Log_Error__c> lstObjB...

Show Hyper Link On Add Error in Salesforce Trigger

Requirement: Check Duplicate record in system and show the add error in form of hyperlink corresponding duplicate record ID Solution : Write a trigger and show add error objExistingRecord >>> OldRecord Id objNewRecord >> New Record  objNewRecord.addError('Same Combination of Record already Inserted in System: <a href=\'/'+ objExistingRecord.id +'\'>'+objExistingRecord.Name+'</a>', false);                                                                           Thanks                                                Sumit Shukla

Schedule Class for every One Hour Everyday in Salesforce

Write below code in "Developer Console" to schedule class for every One Hour Everyday.  Apex Code: NameofScheduleclassEveryhour objschclass =  new NameofScheduleclassEveryhour (); string strSeconds = '0'; string strMinutes = '0'; string strHours = '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23'; string strDay_of_month = '*'; string strMonth = '*'; string strDay_of_week = '?'; String sch = strSeconds + ' ' + strMinutes + ' ' + strHours + ' ' + strDay_of_month + ' ' + strMonth + ' ' + strDay_of_week; system.schedule('ScheduleclassEveryhour', sch, objschclass);                                    Thanks,                               Sumit Shukla

Schedule Apex Class Job Script

Schedule Apex Class Job Script You Can run you job script in two ways 1 ) From UI : Go to Setup -> Apex Classes -> Click on Schedule Apex button  2) From Developer Console, check below  For Monitor : Go to Setup—>Monitor –> Scheduled Jobs Syntax:  Seconds Minutes Hours Day Month Week Year Year is optional. Seconds                         :- 0–59 Minutes                         :- 0–59 Hours                            :- 0–23 Day (Day_of_month)    :- 1–31 Month                            :- 1–12 Week (Day_of_week)     :- 1–7 Year                             :- null or 1970–2099 The followin...

Date Function using in apex

Date Functions are mostly using in apex (Salesforce) addDays(additionalDays) : This function adds the specified number of additional days to a Date. Syntax : public Date addDays(Integer additionalDays) addMonths(additionalMonths) : This function adds the specified number of additional months to a Date . Syntax : public Date addMonths(Integer additionalMonths) addYears(additionalYears) : This function adds the specified number of additional years to a Date . Syntax : public Date addYears(Integer additionalYears) day() : This function returns the day-of-month component of a Date . Syntax : public Integer day() dayOfYear() : This function returns the day-of-year component of a Date . daysBetween(secondDate) : This function returns the number of days between the Date that called the method and the specified date. daysInMonth(year, month) : This function returns the number of days in the month for the specified year and month (1=Jan) . format() : This function r...