Syntax Highlighter JS

Thursday, April 19, 2012

Formula fields that reference record type names across objects

Hard coding record type ID's in validation rules (or apex for that matter), isn't good practice as it will break across instances (i.e. test vs. prod) and is high maintenance.    So it makes sense to just use the record type name right?

Right and you can use record type names in formula fields and that makes perfect sense.  So you create some record types on the opportunity object as pictured.

Then you create a field called record_type_name__c that has a formula of $RecordType.Developer Name.

Next you add a test record and then open up explorer to query the field and make sure the results are correct:

Now you can reference that field in your formulas on the opportunity object without any problem.  What if you want to reference this formula field from another object? 

Please note you can cross reference this formula field in APEX or SOQL, it appears that this behavior is unique to validation rules.  If you were able to create this cross referenced field prior to salesforce putting the error in place then the cross reference field will return the record type of the child object.  Very odd indeed.

The use case here is simple, create a validation rule that checks the record type name of a parent (master detail relationship in my example) object and implement some testing logic.

So goto your child object and setup a formula that references the record type name formula field from the parent (opportunity) object.

But when you hit save you will get this error:
Which claims the field in the referenced formula does not exist.  Note that I didn't type this name into salesforce but instead was allowed to pick it from the list that sales force populated for me.

Due to this error, you simply can't reference record type names across objects in validation rules (even though you can query them like normal fields in SOQL).   This forces you to put this in apex trigger or to cheat and use a workflow rule to update a hidden field with the record type on the object.   Neither is an ideal situation.  The apex trigger adds development and testing time while the workflow rule with hidden field unnecessarily increases data usage just feels like a total hack

If you have a 3rd way or found a way to make this work, please feel free to comment below and let me know.

Wednesday, April 11, 2012

Automatically sending email reminders about pending approvals

06/14/2012 EDIT : Please see the new post for updated SQL to avoid this error: "System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target address (target, to, cc, bcc):"  

The approval process in Salesforce is very handy because you can send e-mail notifications (by template) and allow approvals via email.   However, some users get busy and delete the email without processing it and can't remember to look at a queue to work these items.

So the request often pops up for users to be reminded via email about pending approval requests.  This post is going to show you how to do exactly that.  We are going to create a class to find approvals over a day old and send a reminder email (possibly off of a template) to the user in question.   Then we will create a wrapper class and schedule it to run once every day.

Before we get started, please make sure that you have an active approval process in place for both Opportunities and Accounts.  Failure to have these in place may result in errors and/or lower code coverage.
One of the things we want this class to do is to use email templates to send the reminder.  This allows system administrators to maintain the template without changing the programming.  Since approvals can be submitted on many object types and we only get the ID from the table, we are going to need to discover what type we are dealing with.

You can use a call to DescribeSObjectResult to pull in the type but that is alot of addtional code but the quick and easy way is to just query for the .type.

Here is an example of that and nesting in our default query:

SELECT Id, TargetObject.Name, TargetObjectID, TargetObject.Type, 
(SELECT Id,, Actor.Name FROM WorkItems)  
FROM ProcessInstance  
WHERE Status = 'Pending' AND IsDeleted = False AND SystemModStamp < Today 

Now that we have the object type, we will need to pull in the ID of the email template as needed.   To do this, constants are set at the top of the class (see full class below) and then referenced in the SendReminderEmail method.   You will need to alter this method (around line 66 where the comment is)  to use any new constants that you create.  

So now you have created the templates in the system, created constants for those templates, and referenced the templates in the code just like the OpportunityEmailTemplateName in the example class.  Now you load the class but are getting errors.

Salesforce seems to not allow you to use email templates to send emails to users about other objects but works just fine for contacts.

To get this working, be sure to remove the recipientType from the <messaging:emailTemplate> tag.  If you don't, you will get the error: "INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds"

This step is vital to getting this all to work.   Anyway, here is the full class with test code:

global class ApprovalReminderEmails implements Database.Batchable<sObject>,Database.Stateful { /********************************************************************* Add/Edit these constants to contain your email template names PLEASE NOTE THAT THESE MUST BE VISUALFORCE TEMPLATES TO WORK! Also, the VF template must NOT have recipientType set in the <messaging:emailTemplate> tag or you will get the error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds ***********************************************************************/ static final string OpportunityEmailTemplateName = 'Approval_Opportunity_Reminder'; // this method is used to get all reocrds that will be processed by execute method global Database.QueryLocator start(Database.BatchableContext bc){ // try to use the .type to determine object type in SOQL // instead of DescribeSObjectResult apex code String query = 'SELECT Id, TargetObject.Name, TargetObjectID, TargetObject.Type, (SELECT Id,, Actor.Name FROM WorkItems) FROM ProcessInstance WHERE Status = \'Pending\' AND IsDeleted = False AND SystemModStamp < Today'; if (test.IsRunningTest() == true) { query = 'SELECT Id, TargetObject.Name, TargetObjectID, TargetObject.Type, (SELECT Id,, Actor.Name FROM WorkItems) FROM ProcessInstance WHERE Status = \'Pending\' AND IsDeleted = False'; } // query w/o date when test return Database.getQueryLocator(query); } // querylocator start // find and process all pending approval requests that aren't deleted // and are older than today global void execute(Database.BatchableContext BC, List<sObject> scope) { // loop thru results for (SObject s : scope) { ProcessInstance PI = (ProcessInstance)s; for(ProcessInstanceWorkitem WI : PI.WorkItems) { ApprovalReminderEmails.SendReminderEmail(PI.TargetObject.ID, PI.TargetObject.Type, WI.Actor.Id, WI.Actor.Email, WI.Actor.Name, PI.TargetObject.Name); } // loop thru WorkItems } // loop thru scope which contains the process instance results } // end SendReminders global void finish(Database.BatchableContext info) { } // finish private static void SendReminderEmail(Id TargetID, String TargetObjectType, Id ActorID, string ActorEmailAddress, string ActorName, string TargetDesc) { id EmailTemplateID; // target object type, name and ID will be null in the test methods but work in non test system.debug('TargetObjectType = ' + TargetObjectType); if (TargetObjectType == 'Opportunity') { EmailTemplateID = FindEmailTemplateIDByDeveloperName(OpportunityEmailTemplateName); } /** << Insert code here for other objects & email templates >> **/ // Make sure this transaction won't fail due to lack of daily capacity Messaging.reserveSingleEmailCapacity(1); Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); String[] toAddresses; // email will be null during testing ... if (test.IsRunningTest() == true) { toAddresses = new String[] {''}; } else { toAddresses = new String[] {ActorEmailAddress}; } // prevent Email Exception due to null address during testing if (EmailTemplateID != null) { // use our template email.setTemplateId(EmailTemplateID); email.saveAsActivity = false; // populate the template w/ object data email.setTargetObjectId(ActorID); email.setWhatId(TargetID); } else { // use a generic HTML email when no template is setup / found // get the current salesforce instance to build the link with string domain = URL.getSalesforceBaseUrl().toExternalForm(); string TargetLink = domain + '/' + string.valueof(TargetID); email.setToAddresses(toAddresses); // set the subject on the email email.setSubject('Reminder: Item pending approval'); // set the body of the email email.setHTMLBody('Dear ' + ActorName + ', <br/><br/>' + 'The following ' + TargetObjectType + ' is still pending your approval:<br/>' + TargetDesc + '<br/>' + '<br/> Click this link to view the full record:<br/> ' + '<a href=\'' + TargetLink + '\'>' + TargetLink + '</a>' + '<br/>Please DO NOT reply to this email.' ); } // check for template id // send our email by creating an array of emails and calling the send email method. Messaging.SingleEmailMessage[] EmailsToSend = new Messaging.SingleEmailMessage[] { email }; Messaging.sendEmail(EmailsToSend); } // end send reminder email // this method could be moved to a utility class and made public . . . . public static ID FindEmailTemplateIDByDeveloperName(string DeveloperName) { id EmailTemplateID; List<EmailTemplate> EmailTemplateResults = new List<EmailTemplate>(); if (DeveloperName != null) { EmailTemplateResults = [SELECT Id, Name, DeveloperName, IsActive FROM EmailTemplate WHERE DeveloperName = :DeveloperName]; if (EmailTemplateResults.size() > 0) { if (EmailTemplateResults[0].IsActive == true) { EmailTemplateID = EmailTemplateResults[0].id; } // check for active email template } // check for null search results } // check for blank name return EmailTemplateID; } // FindEmailTemplateIDByDeveloperName static testmethod void TestSendReminderEmails() { /** Create test data - edit as needed for custom rules. If you don't have approval processes in place for your test data, you will get lower code coverage in apex testing I have caught system.DMLException of NO_APPLICABLE_PROCESS to prevent total failure of the test unit. **/ // Create 5 test accounts so that only one (5 Accs + 5 Oppty) // executebatch will be invoked during testing. List <Account> AccountsToInsert = new List<Account>(); for(integer i = 0; i<5; i++) { Account a = new Account(Name='Test Account' + i); AccountsToInsert.add(a); } // loop to create 5 accounts insert AccountsToInsert; // no approval process is defined for account in this code, // so we use it to test the generic / HTML template . . . try { for(Account a: AccountsToInsert) { // Create an approval for the account and submit Approval.ProcessSubmitRequest AccountRequest = new Approval.ProcessSubmitRequest(); AccountRequest.setObjectId(a.ID); Approval.ProcessResult AccountRequestResult = Approval.Process(AccountRequest); System.assert(AccountRequestResult.isSuccess()); } // loop thru accounts submitting them for approval } catch (DMLException e) { system.debug('>>>> NO APPROVAL PROCESS FOR ACCOUNTS!'); } // Create opportunities for the accounts date myDate =; List <Opportunity> OpportunitiesToInsert = new List<Opportunity>(); for(Account a: AccountsToInsert) { Opportunity MyOppty = new opportunity(Name='Test Opportunity for ' +,CloseDate=myDate,StageName='Lead'); MyOppty.AccountId = a.Id; OpportunitiesToInsert.add(MyOppty); } // loop thru accounts insert OpportunitiesToInsert; try { for(Opportunity o: OpportunitiesToInsert) { // create an approval for the opportunity Approval.ProcessSubmitRequest OpptyRequest = new Approval.ProcessSubmitRequest(); OpptyRequest.setObjectId(o.ID); Approval.ProcessResult OpptyRequestResult = Approval.Process(OpptyRequest); System.assert(OpptyRequestResult.isSuccess()); } // loop thru opportunities } catch (DMLException e) { system.debug('>>>> NO APPROVAL PROCESS FOR OPPORTUNTIES!'); } /* End create test data */ test.startTest(); ApprovalReminderEmails ARE = new ApprovalReminderEmails(); // the batch size can be no larger than 10 due to current apex email limits integer batchSize = 10; database.executebatch(ARE, batchSize); //increase code coverage by directly calling the method //since it won't get called in testing due to null values returned during testing only //I am using a standard salesforce sample here but need to change this if you removed the sample ApprovalReminderEmails.FindEmailTemplateIDByDeveloperName('ContactFollowUpSAMPLE'); test.stopTest(); } // end test method } // end class
And here is a wrapper class to use for scheduling: global class ScheduleApprovalReminderEmails implements Schedulable { // Run the job every day at 9 am public static String CRON_EXP = '0 0 9 * * ?'; global void execute(SchedulableContext ctx) { ApprovalReminderEmails ARE = new ApprovalReminderEmails(); // the batch size can be no larger than 10 due to current apex email limits integer batchSize = 10; database.executebatch(ARE, batchSize); } // execute static testmethod void TestcheduleApprovalReminderEmails() { Test.startTest(); // Schedule the test job String jobId = System.schedule('TestScheduleApprovalReminderEmails', ScheduleApprovalReminderEmails.CRON_EXP, new ScheduleApprovalReminderEmails()); // Get the information from the CronTrigger API object CronTrigger ct = [SELECT id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId]; // Verify the expressions are the same System.assertEquals(ScheduleApprovalReminderEmails.CRON_EXP, ct.CronExpression); // Verify the job has not run System.assertEquals(0, ct.TimesTriggered); Test.stopTest(); } // CRON test method } // end ScheduleApprovalReminderEmails class

Tuesday, April 10, 2012

Update account address on lead Conversion

In the last post, we looked at geocaching which was a rather complex topic.  In this post, we are going to look at something alot simpler.

The process to convert a lead to an opportunity allows you to map to an existing organization and/or contact. However, this process will not update the address of the organization by default.  Instead, you must edit the organization's record to update the address.

Assuming you trust the quality of your leads and/or are checking addresses during processing, here is a simple trigger to update organization addresses upon lead conversion.

trigger LeadConvert on Lead (after update) { // Map of Leads by Account ID Map<id,lead> LeadsWithAccountsMap = new Map<id,lead>(); // set of accounts in this update Set<id> AccountSet = new Set<id>(); // Used to update accounts in one DML statement Account[] accountUpdate = new Account[0]; // Loop thru leads in this request for(Lead { // Load the leads into the map so we can pull the data into the accounts later LeadsWithAccountsMap.put(l.ConvertedAccountId, l); AccountSet.add(l.ConvertedAccountId); } // for loop Trigger.New // loop thru accounts in this set for(Account a:[Select Id, BillingStreet, BillingCity, BillingState, BillingPostalCode from Account where Id in :AccountSet]) { if(LeadsWithAccountsMap.get(a.Id) != null){ Lead l = LeadsWithAccountsMap.get(a.Id); a.BillingStreet = l.Street; a.BillingCity = l.City; a.BillingState = l.State; a.BillingPostalCode = l.PostalCode; accountUpdate.add(a); } // leadMap.get(a.Id) != null } // for loop AccountSet update accountUpdate; } // end LeadConvert