Code Sample _ Teach Me Salesforce

download Code Sample _ Teach Me Salesforce

of 6

Transcript of Code Sample _ Teach Me Salesforce

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    1/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/

    Teach Me Salesforce

    A community a pproach to learning salesforce.com

    Archive for the ‘Code Sample’ Category

    Simplest Apex Trigger Patterns

    leave a comment »

    Because sometimes you just want to see the basic programming patterns for Apex and reverse engineer them to fit your needs.

    These two are the most basic trigger patterns. They both do the same thing: set a field’s value on a record when that record is addedto Salesforce. It only happens on insert, not on update because that’s slightly less simple (and a different post). The only difference isone does it Before Insert and one does it After Insert. Why? Because they can. Maybe someday we’ll discuss here why you use oneor the other but today we just want code that works, so here you go:

    Trigger ContactBeforeTrigger on Contact (before insert) {for(Contact c : Trigger.new){

    c.HasOptedOutOfEmail = true;}

    }

    Trigger ContactAfterTrigger on Contact (after insert) {List conList = new List();

    for(Contact conInTrigger : trigger.new){Contact c = new Contact(Id = conInTrigger.Id, HasOptedOutOfEmail = true);conList.add(c);

    }update conList;

    }

    And of course anything you want to use in Production needs a test class, so here you go, one that works for both!

    @isTestpublic Class TestContactTrigger{

    public static testMethod void testContactInsert(){

    Contact aNewContact = new Contact(LastName = 'qwerty');

    Insert aNewContact;

    Contact theInsertedContact = [Select HasOptedOutOfEmail from Contact limit 1];

    System.assert(theInsertedContact.HasOptedOutOfEmail);

    }

    }

    Written by Always Thinkin

    February 28, 2016 at 4:53 pm

    Posted in Apex, Beginner , Code Sample, Trigger , Uncategorized

    Unit Tests: Not Just for Dev – Idea 1

    leave a comment »

    Unit tests offer much more than just the means to get 75%+ code coverage, and they can be used to protect more than just Apex.Read the intro to this series in Idea 0.

    Our first example is the simplest: protecting fields that you don’t want deleted. A use case for this is External Integrations that rely on

    https://teachmesalesforce.wordpress.com/2014/08/03/unit-tests-not-just-for-devs-idea-1/#respondhttps://teachmesalesforce.wordpress.com/2016/02/28/simplest-apex-trigger-patterns/#respondhttps://teachmesalesforce.wordpress.com/2016/02/28/simplest-apex-trigger-patterns/https://teachmesalesforce.wordpress.com/https://teachmesalesforce.wordpress.com/2014/08/03/unit-tests-not-just-for-dev-idea-0/https://teachmesalesforce.wordpress.com/2014/08/03/unit-tests-not-just-for-devs-idea-1/#respondhttps://teachmesalesforce.wordpress.com/2014/08/03/unit-tests-not-just-for-devs-idea-1/https://teachmesalesforce.wordpress.com/category/uncategorized/https://teachmesalesforce.wordpress.com/category/trigger/https://teachmesalesforce.wordpress.com/category/code-sample/https://teachmesalesforce.wordpress.com/category/beginner/https://teachmesalesforce.wordpress.com/category/apex/https://teachmesalesforce.wordpress.com/2016/02/28/simplest-apex-trigger-patterns/#respondhttps://teachmesalesforce.wordpress.com/2016/02/28/simplest-apex-trigger-patterns/https://teachmesalesforce.wordpress.com/

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    2/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/ 2

    Salesforce fields. If someone tries to delete the fields, you want to ensure that they are alerted to the impact. By including the fields

    Current Generators and SIC Code in the example Unit Test below, an attempt to delete the fields will throw an error referencing theunit test.

    Let’s describe what’s happening here.

    We start off with the all-important @isTest flag. This tells Salesforce that the Apex Class contains only test Methods. That meansnothing you do in the Class will be saved to the server, and will not delete or change anything on the server. It also means you cannotuse most records that exist on the server, so you have to create your own test records.

    @isTest means that Salesforce will recognize it as a test Class, and when you Run All Tests, it will know to run this test too.

     Next is the Class Name, UnitTest1 and its access modifier is set to “private”. Access modifiers are irrelevant for Unit Tests, private ithe default.

    The actual test Method here is protectFields(). Your test exists between the curly braces {}. Here you must create your test recordsand perform any actions you want tested. The critical item here is “testMethod” which ensures that Salesforce recognizes the methodas performing tests. Without this, Salesforce will not report a test failure regardless of the outcome.

    In this case we are creating a Lead. We are using standard Apex code to create a Lead, to populate fields on that Lead, and finally touse DML to insert the Lead. Required fields and Validation Rules will get enforced when you create the Lead, so be sure to includeany fields affected by them.

    Once this Unit Test is saved to the server, any attempt to delete the field or change its data type will be blocked with a reference tothis Unit Test.

    For this limited scenario, that’s all we need!

    Written by Always Thinkin

    August 3, 2014 at 3:53 pm

    Posted in Apex, Code Sample, Intermediate

    Tagged with Apex, Unit Test

    Salesforce Trigger when Rollups Summaries Not Possiblewith 6 comments

    Master-Details relationships in Force.com are very handy but don’t fit every scenario. For instance, it’s not possible to implement arollup summary on formula field or text fields. Here’s a small trigger that you can use for a starter for these types of situations. Thecode for each class is available at GitHub for your forking pleasure.

    So here’s the (not very useful) use case. Sales Order is the Master object which can have multiple Sales Order Items (detail object).The Sales Order Item has a “primary” Boolean field and a “purchased country” field. Each time Sales Order Items are inserted or updated, if the Sales Order Item is marked as “primary” then the value of “purchased country” is written into the “primary country”field on the Sales Order. I’m assuming that there can only be one Sales Order Item per Sales Order that is marked as

     primary. Essentially this is just a quick reference on the Sales Order to see which country is primary on any of the multiple SalesOrder Items. Not very useful but illustrative.

    1234567

    89

    101112131415

    @isTestprivate class  UnitTest1 {  static  testMethod void  protectFields(){ 

    /*Create a new Lead, populating any Fields you need to protect  * In this case, we want to ensure Current Generators and SIC Code cannot be deleted  * or the field type changed by including them in this Apex Unit Test

      */  Lead l = new  Lead(Company = 'Test Lead',  LastName = 'Lead Last Name',  CurrentGenerators__c = 'Generator X',  SICCode__c = '1234‐ABC');  insert l;  }}

    https://github.com/jeffdonthemic/Blog-Sample-Codehttp://www.salesforce.com/us/developer/docs/api/Content/relationships_among_objects.htmhttps://teachmesalesforce.wordpress.com/2011/08/23/salesforce-trigger-when-rollups-summaries-not-possible/#commentshttps://teachmesalesforce.wordpress.com/2011/08/23/salesforce-trigger-when-rollups-summaries-not-possible/https://teachmesalesforce.wordpress.com/tag/unit-test/https://teachmesalesforce.wordpress.com/tag/apex/https://teachmesalesforce.wordpress.com/category/intermediate/https://teachmesalesforce.wordpress.com/category/code-sample/https://teachmesalesforce.wordpress.com/category/apex/

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    3/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/ 3

    The code is broken down into a Trigger and an Apex “handler” class that implements the actual functionality. It’s best practice toonly have one trigger for each object and to avoid complex logic in triggers. To simplify testing and resuse, triggers should delegateto Apex classes which contain the actual execution logic. See Mike Leach’s excellent trigger template for more info.

    SalesOrderItemTrigger (source on GitHub) – Implements trigger functionality for Sales Order Items. Delegates responsibility toSalesOrderItemTriggerHandler.

    trigger SalesOrderItemTrigger on Sales_Order_Item__c (after insert, after update) {

    SalesOrderItemTriggerHandler handler = new SalesOrderItemTriggerHandler();

    if(Trigger.isInsert && Trigger.isAfter) {handler.OnAfterInsert(Trigger.new);

    } else if(Trigger.isUpdate && Trigger.isAfter) {handler.OnAfterUpdate(Trigger.old, Trigger.new, Trigger.oldMap, Trigger.newMap);

    }

    }

    SalesOrderItemTriggerHandler (source on GitHub) – Implements the functionality for the sales order item trigger after insert andafter update. Looks at each sales order item and if it is marked as primary_item__c then moves the primary_country__c value fromthe sales order item to the associated sales order’s primary_country__c field.

    public with sharing class SalesOrderItemTriggerHandler {

    // update the primary country when new records are inserted from triggerpublic void OnAfterInsert(List newRecords){

    updatePrimaryCountry(newRecords);}

    // update the primary country when records are updated from triggerpublic void OnAfterUpdate(List oldRecords,

    List updatedRecords, Map oldMap,

    Map newMap){updatePrimaryCountry(updatedRecords);

    }

    // updates the sales order with the primary purchased country for the itemprivate void updatePrimaryCountry(List newRecords) {

    // create a new map to hold the sales order id / country valuesMap salesOrderCountryMap = new Map();

    // if an item is marked as primary, add the purchased country// to the map where the sales order id is the keyfor (Sales_Order_Item__c soi : newRecords) {

    if (soi.Primary_Item__c)salesOrderCountryMap.put(soi.Sales_Order__c,soi.Purchased_Country__c);

    }

    https://github.com/jeffdonthemic/Blog-Sample-Code/blob/master/salesforce/src/classes/SalesOrderItemTriggerHandler.clshttps://github.com/jeffdonthemic/Blog-Sample-Code/blob/master/salesforce/src/triggers/SalesOrderItemTrigger.triggerhttp://www.embracingthecloud.com/2010/07/08/ASimpleTriggerTemplateForSalesforce.aspxhttp://blog.jeffdouglas.com/2010/10/21/force-com-programming-best-practices/https://teachmesalesforce.files.wordpress.com/2011/08/sales-order-item.png

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    4/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/ 4

     // query for the sale orders in the context to updateList orders = [select id, Primary_Country__c from Sales_Order__c

    where id IN :salesOrderCountryMap.keyset()];

    // add the primary country to the sales order. find it in the map// using the sales order's id as the keyfor (Sales_Order__c so : orders)

    so.Primary_Country__c = salesOrderCountryMap.get(so.id);

    // commit the recordsupdate orders;

    }

    }

    Test_SalesOrderItemTriggerHandler (source on GitHub) – Test class for SalesOrderItemTrigger andSalesOrderItemTriggerHandler. Achieves 100% code coverage.

    @isTestprivate class Test_SalesOrderItemTriggerHandler {

    private static Sales_Order__c so1;private static Sales_Order__c so2;

    // set up our data for each test methodstatic {

    Contact c = new Contact(firstname='test',lastname='test',email='[email protected]');insert c;

    so1 = new Sales_Order__c(name='test1',Delivery_Name__c=c.id);so2 = new Sales_Order__c(name='test2',Delivery_Name__c=c.id);

    insert new List{so1,so2};

    }

    static testMethod void testNewRecords() {

    Sales_Order_Item__c soi1 = new Sales_Order_Item__c();soi1.Sales_Order__c = so1.id;soi1.Quantity__c = 1;

    soi1.Description__c = 'test';soi1.Purchased_Country__c = 'Germany';

    Sales_Order_Item__c soi2 = new Sales_Order_Item__c();soi2.Sales_Order__c = so1.id;soi2.Quantity__c = 1;soi2.Description__c = 'test';soi2.Purchased_Country__c = 'France';soi2.Primary_Item__c = true;

    Sales_Order_Item__c soi3 = new Sales_Order_Item__c();soi3.Sales_Order__c = so2.id;soi3.Quantity__c = 1;soi3.Description__c = 'test';soi3.Purchased_Country__c = 'Germany';soi3.Primary_Item__c = true;

    Sales_Order_Item__c soi4 = new Sales_Order_Item__c();soi4.Sales_Order__c = so2.id;soi4.Quantity__c = 1;soi4.Description__c = 'test';soi4.Purchased_Country__c = 'Germany';

    Sales_Order_Item__c soi5 = new Sales_Order_Item__c();soi5.Sales_Order__c = so2.id;soi5.Quantity__c = 1;soi5.Description__c = 'test';soi5.Purchased_Country__c = 'Italy';

    insert new List{soi1,soi2,soi3,soi4,soi5};

    System.assertEquals(2,[select count() from Sales_Order_Item__c where Sales_Order__c = :so1.id]);

    https://github.com/jeffdonthemic/Blog-Sample-Code/blob/master/salesforce/src/classes/Test_SalesOrderItemTriggerHandler.cls

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    5/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/ 5

      System.assertEquals(3,[select count() from Sales_Order_Item__c where Sales_Order__c = :so2.id]);

    System.assertEquals('France',[select primary_country__c from Sales_Order__c where id = :so1.id].primary_country__c)System.assertEquals('Germany',[select primary_country__c from Sales_Order__c where id = :so2.id].primary_country__c

    }

    static testMethod void testUpdatedRecords() {

    Sales_Order_Item__c soi1 = new Sales_Order_Item__c();soi1.Sales_Order__c = so1.id;soi1.Quantity__c = 1;soi1.Description__c = 'test';soi1.Purchased_Country__c = 'Germany';

    Sales_Order_Item__c soi2 = new Sales_Order_Item__c();soi2.Sales_Order__c = so1.id;soi2.Quantity__c = 1;soi2.Description__c = 'test';soi2.Purchased_Country__c = 'France';soi2.Primary_Item__c = true;

    insert new List{soi1,soi2};

    // assert that the country = FranceSystem.assertEquals('France',[select primary_country__c from Sales_Order__c where id = :so1.id].primary_country__c)

    List items = [select id, purchased_country__c from Sales_Order_Item__cwhere Sales_Order__c = :so1.id and primary_item__c = true];

    // change the primary country on the sales order item. should trigger updateitems.get(0).purchased_country__c = 'Denmark';

    update items;// assert that the country was successfully changed to DenmarkSystem.assertEquals('Denmark',[select primary_country__c from Sales_Order__c where id = :so1.id].primary_country__c

    }

    }

    Written by Jeff Douglas

    August 23, 2011 at 9:00 am

    Posted in Apex, Code Sample, Trigger 

    JavaScript Remoting

    with 2 comments

    One of the major enhancements from visualforce this release(Summer 11) and my favorite is JavaScript remoting.

    JavaScript Remoting is the ability to invoke apex class method from javascript embedded in a visualforce page.JavaScript Remotingis now available after summer 11 release.

    Here is a quick example : we have a Apex class which defines a get Account method.

    global with sharing class MyJSRemoting{

    public static Account account { get; set; }

    @RemoteActionglobal static Account getAccount(String accountName) {

    account = [select id, name, phone, type, numberofemployees fromAccount where name = :accountName limit 1];

    return account;}

    }

    This method is having @RemoteAction annotation making it available to be called from a visualforce page. Now in our visualforce page we have a script tag set which is how we embed javascript within visualforce pages.

    https://teachmesalesforce.wordpress.com/2011/06/19/javascript-remoting/#commentshttps://teachmesalesforce.wordpress.com/2011/06/19/javascript-remoting/https://teachmesalesforce.wordpress.com/category/trigger/https://teachmesalesforce.wordpress.com/category/code-sample/https://teachmesalesforce.wordpress.com/category/apex/

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    6/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/ 6

    function getAccountJS() {

    var accountNameJS = document.getElementById('accountname').value;

    ankit.MyJSRemoting.getAccount( accountNameJS, function(result, event){

    if (event.status){

    document.getElementById("{!$Component.theBlock.pbs.pbsi2.accId}").innerHTML = result.Id;

    document.getElementById("{!$Component.theBlock.pbs.pbsi1.name}").innerHTML = result.Name;

    }}, {escape:true});

    }

    Get Account

     

    This JavaScript code then invokes the getAccount method in the apex class to take action.

    Please note I have used namespace “ankit.MyJSRemoting” as there is a namespace registered on my organization.

    JavaScript Remoting is the feature which is primarily be used by developers and will allow them to create richer and more interactiveuser interfaces that everyone will benefit from.

    In particular, lets developers create rich javascript based user interfaces by invoking apex controller methods within JavaScript code.JavaScript is typically used to render small parts of user interface. Result from a Javascript remoting call are much faster then usinga typical visualforce reRender model, developers can provide more instant feedback to the user. This is because remoting calls arestateless. Means only data is set back and forth instead a lot of bulky HTML.

    Additional Visualforce enhancements :

    1) Filtered Lookup via Visualforce.2) Inline editing for rich text area field.3) Field Set property accessors.

    This is a cross post to my Blog.

    Written by Ankit Arora (forceguru)

    June 19, 2011 at 4:33 pm

    Posted in Advanced, Apex, Code Sample, Visualforce

    Visualforce Code Generator

    with 9 comments

    This is a cross post from my Blog Post.

    We know how much important role visualforce plays in our application. There are many instance where we need to create a

    http://forceguru.blogspot.com/2011/06/visualforce-code-generator.htmlhttps://teachmesalesforce.wordpress.com/2011/06/15/visualforce-code-generator/#commentshttps://teachmesalesforce.wordpress.com/2011/06/15/visualforce-code-generator/https://teachmesalesforce.wordpress.com/category/visualforce/https://teachmesalesforce.wordpress.com/category/code-sample/https://teachmesalesforce.wordpress.com/category/apex/https://teachmesalesforce.wordpress.com/category/advanced/http://forceguru.blogspot.com/2011/06/summer-11-features-part-2-javascript.html

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    7/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/ 7

    visualforce page and apex class. Salesforce provides powerful tools like workflows, approvals, validation etc. from which we canimplement our business functionalities with just button clicks.

     Now I was having a requirement where I need to create many visualforce pages, some are custom and some are cloning native pagewith native layouts with some small changes. This just clicked me to create a tool from which we can create a visualforce page codewith just clicking buttons. Yes!! Visualforce page code with button click.

    This saved a lot of time, as I do not need to write any thing to create a heavy visualforce page and amazingly it is done just using button clicks.

    Install the package : https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000Pqos

    Just append “/apex/vfgenerator__codegenerator” in URL.

     Now let me jump into the explanation what exactly I have done. A simple UI will be displayed, where user can select the desired typof page, object name, record type, email field.

    Object Name : Valid object API name (include namespace if any)

    Record Type : Record type Id of object selected in Object NameType of Page :

    1. Edit : Code will be generated for the edit page of the object (according to “record type” layout if selected any).2. Detail : Code will be generated for the detail page of the object (according to “record type” layout if selected any)3. Custom Detail : Code will be generated for detail page according to the fields selected from UI4. Custom Edit : Code will be generated for edit page according to the fields selected from UI

    In the above screen I have selected “Edit” as the type of page and “Account” in object, also provided my email. When I click “Generate Code” it displays like this :

    Just copy the code and paste it in new visualforce page. Why I have given my email id because when you paste the code invisualforce page it will loose all the formatting and will display in one single line, but code sent on email will come with formatting.So we can copy the generated code from email also. Now when you hit the newly created visualforce page it will display all fields in

    edit mode which are displayed on native edit page. Isn’t that good?

     Now lets try creating some custom visualforce page. Select “Custom Edit” in “Type of Page” and “Account” in “Object Name”. Itwill display a section “Select Fields”. Click on “Display Fields”, it will display all fields which are up datable by present user.

    https://teachmesalesforce.files.wordpress.com/2011/06/screen-22.jpghttps://teachmesalesforce.files.wordpress.com/2011/06/screen-1.jpghttps://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000Pqoshttp://www.salesforce.com/

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    8/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/ 8

    Select some fields and click on “Generate Code”. Again copy paste the code in your visualforce page, it will display selected fieldsin edit mode.

     Now heavy visualforce pages are created with just button clicks.

    Package provided is managed because the tool is under testing and I would like to have feedback from you all. Once it is free from al bugs I will provide the code.

    Declaration: You may find similar post related to “Visualforce Code Generator”. The end result may be similar but there is aconsiderable difference in the approaches being followed here. So I, hereby declare that my project is entirely my own creation andhas not been copied from any other person/organization’s words or idea. Please feel free to drop me an email at“[email protected]” if there is any disagreement.

    Cheers

    Written by Ankit Arora (forceguru)

    June 15, 2011 at 2:32 pm

    Posted in Advanced, Apex, Code Sample, Intermediate, Visualforce

    Tagged with Code, Generator , Send Email

    How Salesforce 18 Digit Id Is Calculated

    with 6 comments

    As we know that each record Id represents a unique record within an organization. There are two versions of every record Id insalesforce :

    15 digit case-sensitive version which is referenced in the UI18 digit case-insensitive version which is referenced through the API

    The last 3 digits of the 18 digit Id is a checksum of the capitalization of the first 15 characters, this Id length was created as aworkaround to legacy system which were not compatible with case-sensitive Ids. The API will accept the 15 digit Id as input but willalways return the 18 digit Id.

     Now how we can calculate the 18 digit Id from 15 digit Id ??? Just copy paste the below code in system logs and pass your 15 digit iin String id

    //Your 15 Digit IdString id= '00570000001ZwTi' ;

    string suffix = '';integer flags;

    for (integer i = 0; i < 3; i++){

    flags = 0;for (integer j = 0; j < 5; j++){

    string c = id.substring(i * 5 + j,i * 5 + j + 1);//Only add to flags if c is an uppercase letter:if (c.toUpperCase().equals(c) && c >= 'A' && c

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    9/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/ 9

      }if (flags

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    10/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/ 10

      global Database.QueryLocator start(Database.BatchableContext BC){

    //Creating map of user id with cases logged today by themfor(Case c : allCaseLoggedToday){

    if(userCaseMap.containsKey(c.CreatedById)){

    //Fetch the list of case and add the new case in itList tempList = userCaseMap.get(c.CreatedById) ;tempList.add(c);//Putting the refreshed case list in mapuserCaseMap.put(c.CreatedById , tempList) ;

    }else{

    //Creating a list of case and outting it in mapuserCaseMap.put(c.CreatedById , new List{c}) ;

    }}

    //Batch on all system admins (sales rep)String query = 'select id , name , Email from User

    where Profile.Name = \'System Administrator\'';return Database.getQueryLocator(query);

    }

    global void execute(Database.BatchableContext BC, List scope){

    for(Sobject s : scope){

    //Type cast sObject in user objectUser ur = (User)s ;

    //If system admin has logged any case today then only mail will be sentif(userCaseMap.containsKey(ur.Id)){

    //Fetching all cases logged by sys adminList allCasesOfSalesRep = userCaseMap.get(ur.Id) ;

    String body = '' ;//Creating tabular format for the case detailsbody = BodyFormat(allCasesOfSalesRep) ;

    //Sending MailMessaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage() ;

    //Setting user email in to addressString[] toAddresses = new String[] {ur.Email} ;

    // Assign the addresses for the To and CC lists to the mail objectmail.setToAddresses(toAddresses) ;

    //Email subject to be changedmail.setSubject('New Case Logged');

    //Body of emailmail.setHtmlBody('Hi ' + ur.Name + ',

    Details of Cases logged today is as follows :

    ' + body + 'Thanks');

    //Sending the emailMessaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    }}

    }

    public String BodyFormat(List lst){

    String str = '' ;for(Case cs : lst){

    str += ''+ cs.CaseNumber +''+''+ cs.Owner.Name+''+''+ cs.Account.Name +''

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    11/12

    3/4/2016 Code Sample | Teach Me Salesforce

    https://teachmesalesforce.wordpress.com/category/code-sample/ 1

      +''+ cs.Contact.Name +''+'' ;}str = str.replace('null' , '') ;String finalStr = '' ;finalStr = ' CaseNumber Owner

    Account Contact ' + str +'' ;return finalStr ;

    }

    global void finish(Database.BatchableContext BC){}

    }

    Code is self explanatory, hope there will be no issues understanding it.

    Execute this class using below script in system logs :

    Batch_CaseEmail controller = new Batch_CaseEmail() ;Integer batchSize = 1;database.executebatch(controller , batchSize);

    All system administrators will get an email something like this :

    Written by Ankit Arora (forceguru)

    June 5, 2011 at 2:12 pm

    Posted in Advanced, Apex, Code Sample

    Tagged with Batch Class, Governor Limits, Salesforce Batch Apex, Sending Emails

    « Older Entries

    Recent Posts

    Simplest Apex Trigger PatternsApex Homework Assignment 1: Control Flow – If Statements and For LoopsApex Homework Assignment 0: Collections – Lists, Sets and MapsUnit Tests: Not Just for Dev – Idea 1Unit Tests: Not Just for Dev – Idea 0

    Search

      Search

    Categories

    Advanced (7)Apex (17)Approval Process (1)Beginner  (10)CloudSpokes (1)Code Sample (10)Configuration (7)Google (1)Intermediate (9)REST (1)

    https://teachmesalesforce.wordpress.com/category/rest/https://teachmesalesforce.wordpress.com/category/intermediate/https://teachmesalesforce.wordpress.com/category/google/https://teachmesalesforce.wordpress.com/category/configuration/https://teachmesalesforce.wordpress.com/category/code-sample/https://teachmesalesforce.wordpress.com/category/cloudspokes/https://teachmesalesforce.wordpress.com/category/beginner/https://teachmesalesforce.wordpress.com/category/approval-process/https://teachmesalesforce.wordpress.com/category/apex/https://teachmesalesforce.wordpress.com/category/advanced/https://teachmesalesforce.wordpress.com/2014/08/03/unit-tests-not-just-for-dev-idea-0/https://teachmesalesforce.wordpress.com/2014/08/03/unit-tests-not-just-for-devs-idea-1/https://teachmesalesforce.wordpress.com/2015/06/21/apex-homework-assignment-0-collections-lists-sets-and-maps/https://teachmesalesforce.wordpress.com/2015/06/23/apex-homework-assignment-1-control-flow-if-statements-and-for-loops/https://teachmesalesforce.wordpress.com/2016/02/28/simplest-apex-trigger-patterns/https://teachmesalesforce.wordpress.com/category/code-sample/page/2/https://teachmesalesforce.wordpress.com/tag/sending-emails/https://teachmesalesforce.wordpress.com/tag/salesforce-batch-apex/https://teachmesalesforce.wordpress.com/tag/governor-limits/https://teachmesalesforce.wordpress.com/tag/batch-class/https://teachmesalesforce.wordpress.com/category/code-sample/https://teachmesalesforce.wordpress.com/category/apex/https://teachmesalesforce.wordpress.com/category/advanced/https://teachmesalesforce.wordpress.com/2011/06/05/sending-more-than-10-e-mails/email/

  • 8/20/2019 Code Sample _ Teach Me Salesforce

    12/12

    3/4/2016 Code Sample | Teach Me Salesforce

    Trigger  (6)Uncategorized (6)Validation (1)Visualforce (5)Workflow (1)

    Contributors

    Pages

    AboutPosting Guidelines

    Blogroll

    Appirio Tech BlogCloudSpokes BlogJeff Douglas' Blog

    Stay in touch

    Follow on LinkedinFollow on Twitter Like on Facebook 

    Email Subscription

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 254 other followers

    Enter your email address

    Sign me up!

    Meta

    Register Log in

    https://teachmesalesforce.wordpress.com/wp-login.phphttps://wordpress.com/start?ref=wploginhttp://www.facebook.com/pages/TeachMeSalesforce/113725382053803?sk=infohttp://twitter.com/teachmesfdchttp://uk.linkedin.com/groups/Teach-Me-Salesforce-3953845http://blog.jeffdouglas.com/http://blog.cloudspokes.com/http://techblog.appirio.com/https://teachmesalesforce.wordpress.com/posting-guidelines/https://teachmesalesforce.wordpress.com/about/https://teachmesalesforce.wordpress.com/author/sidkabe/https://teachmesalesforce.wordpress.com/author/sfdcnerd/https://teachmesalesforce.wordpress.com/author/salescheck/https://teachmesalesforce.wordpress.com/author/pbattisson/https://teachmesalesforce.wordpress.com/author/luneos/https://teachmesalesforce.wordpress.com/author/lukecushanick/https://teachmesalesforce.wordpress.com/author/knthornt/https://teachmesalesforce.wordpress.com/author/kenji776/https://teachmesalesforce.wordpress.com/author/jeffdonthemic/https://teachmesalesforce.wordpress.com/author/forceguru/https://teachmesalesforce.wordpress.com/author/crmfyi/https://teachmesalesforce.wordpress.com/category/workflow/https://teachmesalesforce.wordpress.com/category/visualforce/https://teachmesalesforce.wordpress.com/category/validation/https://teachmesalesforce.wordpress.com/category/uncategorized/https://teachmesalesforce.wordpress.com/category/trigger/