Force.

com Workbook: Summer '11

Force.com Workbook

Last updated: July 10, 2011
© Copyright 2000-2011 salesforce.com, inc. All rights reserved. Salesforce.com is a registered trademark of salesforce.com, inc., as are other

names and marks. Other marks appearing herein may be trademarks of their respective owners.

Table of Contents

Table of Contents
About the Force.com Workbook...........................................................................................................................................................3 Tutorial #1: Creating a Warehouse Application....................................................................................................................................5 Step 1: Create a Merchandise Custom Object..........................................................................................................................5 Step 2: Add Description, Price, and Total Inventory Fields......................................................................................................7 Step 3: Create a Tab................................................................................................................................................................10 Step 4: Create a Warehouse App.............................................................................................................................................11 Step 5: Create a Merchandise Record.....................................................................................................................................12 Summary.................................................................................................................................................................................13 Tutorial #2: Adding Relationships......................................................................................................................................................14 Step 1: Create an Invoice Statement Custom Object..............................................................................................................14 Step 2: Create a Line Item Object...........................................................................................................................................17 Step 3: Relate the Objects.......................................................................................................................................................18 Step 4: Add Invoice Statements to the App............................................................................................................................19 Step 5: Create an Invoice Record............................................................................................................................................19 Summary.................................................................................................................................................................................21 Tutorial #3: Using Formulas and Validation Rules..............................................................................................................................22 Step 1: Calculate a Value for Each Line Item..........................................................................................................................22 Step 2: Calculate a Value for the Invoice Statement With a Roll-Up Summary Field............................................................23 Step 3: Check Inventory With a Validation Rule....................................................................................................................24 Step 4: Test the Validation Rule..............................................................................................................................................26 Step 5: Improve the Validation Rule........................................................................................................................................27 Summary.................................................................................................................................................................................28 Tutorial #4: Creating Reports and Dashboards...................................................................................................................................29 Step 1: Add Reports and Dashboards to the Warehouse App.................................................................................................29 Step 2: Create a Tabular Report..............................................................................................................................................29 Step 3: Create a Summary Report...........................................................................................................................................31 Step 4: Create a Matrix Report...............................................................................................................................................33 Step 5: Create a Dashboard.....................................................................................................................................................35 Summary.................................................................................................................................................................................37 Tutorial #5: Automating Processes Using Workflow...........................................................................................................................38 Step 1: Populate the Line Item Price Using a Workflow Rule................................................................................................38 Step 2: Update Total Inventory When an Order is Placed......................................................................................................41 Step 3: Test the Workflow Rules.............................................................................................................................................42 Summary.................................................................................................................................................................................43 Tutorial #6: Creating an Approval Process..........................................................................................................................................44 Step 1: Create a User...............................................................................................................................................................44 Step 2: Create an Approval Process.........................................................................................................................................45 Step 3: Create a Custom Profile..............................................................................................................................................47 Step 4: Create a User...............................................................................................................................................................48 Step 5: Test the Approval Process............................................................................................................................................49 Summary.................................................................................................................................................................................51

i

..........................................................85 Summary........................................................................58 Step 2: Add Test Methods to the Class...............................74 Tutorial #10: Creating a Public Web Page Using Sites..........................................................................................................70 Step 6: Add Inline Editing Support...................com Domain Name..........................................................................................................................................................................................................................................................................................................75 Step 2: Register a Force................................................................................................................................................................................................................................................................................................................82 Step 3: Create the Store Front..................................................................................................................................................................59 Step 3: Write Code to Execute the Trigger...........................................................................................................................56 Summary.........com Site..........60 Step 4: Execute the Test...............................................................................................................................................................................................81 Step 2: Add Methods to the Controller......................................................................67 Step 4: Add a Controller to the Page.................................................................................65 Step 1: Enable Visualforce Development Mode...................................................................................................................................................................................................................................................................................................................................................................52 Step 1: Create an Apex Trigger Definition.......80 Tutorial #11: Creating a Store Front............................................................................................................................................................................................................................................................................................................................................................................................78 Step 4: Configure and Test the Site..........................................................................................com IDE.........................................................................................................84 Step 4: Bonus Step—Updating the Page with AJAX.......................69 Step 5: Display the Inventory Count Sheet as a Visualforce Page...........57 Tutorial #8: Adding Tests to Your Application................................................................................................................................................................................................................................64 Tutorial #9: Building a Custom User Interface Using Visualforce..........................................................................................................................................................................................................................................................................................................................................75 Step 1: Create a Product Catalog Page...........................................................................58 Step 1: Create an Apex Test Class...............................................................................................................................62 Summary...........................................................................................78 Summary...............................................................................................................................................................54 Step 3: Iterate Through the List and Modify Price..............................................................................................................Table of Contents Tutorial #7: Adding Programmatic Logic with Apex............................................................................................................................................................88 ii ..................................................................77 Step 3: Create a Force.........................................................................................................................81 Step 1: Create a Controller..................................................................................................................................................................................................................65 Step 2: Create a Visualforce Page.......................................................................................................................................................87 Appendix..............................................................55 Step 4: Test the Trigger..................88 Creating a Project in the Force............................................................................................................................88 Delivering Your Application.........................................................................................66 Step 3: Add a Stylesheet Static Resource.......................................................................................61 Step 5: View Code Coverage and Improve Tests............................................................................................................................................................72 Summary.....................................................................................................................53 Step 2: Define a List Variable......................

7.com Workbook About the Force. Google Chrome applies updates automatically.com Workbook shows you how to create an application in a series of tutorials. see the Force. see “Configuring Internet Explorer” in the Salesforce online help. While you can use the Force. and Salesforce admins who want to delve more deeply into application development using coding.com strongly recommends using Internet Explorer version 8 over versions 6 and 7.com Workbook The Force. approvals to send email notifications for large invoice values.com.com makes every effort to test and support the current version of Google Chrome.com Platform Fundamentals for point-and-click application development. and trigger logic to update the prices in open invoices. Supported Browsers Browser Windows® Internet Explorer® versions 6. For configuration recommendations. You'll start developing the application from the bottom up. most applications share certain characteristics such as: • • • • A database to model the information in the application Business logic and workflow to carry out particular tasks under certain conditions A user interface to expose data and functionality to those logged in to your application A public website to show data and functionality on the Web The tutorials are centered around building a very simple warehouse management system. and 8 Comments Salesforce. Mozilla® Firefox® version 3. Apply all Microsoft® hotfixes. you'll first build a database model for keeping track of merchandise. Salesforce. For configuration recommendations.com platform to build virtually any kind of application. that is. you'll create a user interface to display a product inventory to staff. but it's all quite easy—as you'll soon see. Intended Audience This workbook is intended for developers new to the Force.About the Force. It may sound like a lot. You'll continue by adding business logic: validation rules to ensure that there is enough stock.com recommends using Firefox for best performance. Salesforce. and then the start of a simple store front. There are no configuration recommendations for Chrome. see “Configuring Firefox” in the Salesforce online help. workflow to update inventory when something is sold.6 Google® Chrome™ version 10 3 . If you're an admin just getting started with Force. Each of the tutorials builds on the previous tutorial to advance the application's development and simultaneously showcase a particular feature of the platform. a public website to display a product catalog.com platform. Once the database and business logic are complete.

2. There are no configuration recommendations for Safari. or even an email that you use. 4 . or DE org for short. 7. and install apps. The Username field is also in the form of an email address.force. However. see “Installing Google Chrome Frame for Internet Explorer” in the Salesforce online help.0. 1. Enter the Captcha words shown and click Submit Registration. Read and then select the checkbox for the Master Subscription Agreement. For configuration recommendations. You can find the latest version of this Workbook and additional tutorials that extend the app at developer. In the Email Address field. there's a lot of useful information here and some additional steps to flesh out your app. 5. At the end of each step there is an optional Tell Me More section. Supported on Windows XP and Mac OS X version 10.. • • To learn more about Force.. make sure to use a public email address where you can easily check your email from a Web browser.force.org. In a moment you'll receive an email with a login link. In your browser go to http://developer. 6. If you like to do things quickly. 3. It's helpful to change the username to something that describes the use of the org.x Comments Supported plug-in for Internet Explorer 6 only. but it does not have to be the same as your actual email address. 4. if you're a smell-the-roses type.force.com and to access a rich set of resources. Click the link and change your password.com. test. such as dev@workbook. DE orgs are multipurpose environments with all of the features and permissions that allow you to develop. Fill in the fields about you and your company.. package. Tell Me More. visit Developer Force at developer.com/join.About the Force. Before You Begin This workbook is designed to be used with a Developer Edition organization.4 and later. move on to the next step.com/workbook.com Workbook Browser Google Chrome Frame plug-in for Internet Explorer 6 Apple® Safari® version 5.

On the Force. The first step is to create a custom object that will hold information about merchandise. such as its name. Duration: 20-30 minutes At the heart of this application is what you want to sell: merchandise. price. Price. When you complete this tutorial. you can think of a custom object as representing a table. An object comes with standard fields. 5 . See Also: Step 1: Create a Merchandise Custom Object Step 2: Add Description. description. But you can also add your own fields to track or list just about anything you can think of. and price of all your merchandise. If you are familiar with databases. these data objects are called custom objects. but you can also create custom objects to track anything you want. a tab. view and edit information about the object. and then click Create ➤ Objects in the sidebar menu to display the Custom Objects page.Tutorial #1: Creating a Warehouse Application Tutorial #1: Creating a Warehouse Application Level: Beginner. as well as screens that allow you to view and edit all of this information. and a custom object that tracks the name. and screens that allow you to list.salesforce. Enter your username (in the form of an email address) and password. Click Your Name ➤ Setup in the upper right corner. So you'll begin by creating a data object that keeps track of all the elements of a particular merchandise item. you will have a working application with its own menu. description. and Total Inventory Fields Step 3: Create a Tab Step 4: Create a Warehouse App Step 5: Create a Merchandise Record Summary Step 1: Create a Merchandise Custom Object The Force. 2. 1. and so on. Launch your browser and go to https://login.com.com platform includes predefined standard objects.com platform. 3.

select Allow Reports (you'll create reports in a later tutorial). 6 . Fill in the custom object definition. Click New Custom Object to display the New Custom Object wizard. For the Plural Label. enter Merchandise. Click Save to finish creating your new object. enter Merchandise. 5. 6.Tutorial #1: Creating a Warehouse Application 4. In the Optional Features section. • • • For the Label.

See Also: Tutorial #1: Creating a Warehouse Application Step 2: Add Description. Custom fields—You haven't defined any custom fields yet. 1. such as a description. and other neat features to this custom object... these are called standard fields.. but one is generated for you. You can add custom fields to list or track just about anything you can think of. which means it will automatically track who created each record. and Total Inventory Fields Step 2: Add Description. Soon you'll be adding fields. Create the Description field. Follow the steps below to create custom fields for the description. which differentiates them from standard objects and makes them easier to identify. and how many are in stock. This name is how you reference the object programmatically. you'll do that in the next step. Take a look at the following image to familiarize yourself with the Merchandise custom object. how much it costs. • • • • Merchandise detail page—This page shows you everything you need to know about your Merchandise custom object. and Total Inventory Fields A merchandise object should have fields that are used for tracking various information. the Merchandise object has a standard field for Owner. and inventory. you're right. 7 . After you save the new custom object. validation rules. All custom objects end in __c. Standard fields—Some fields are generated automatically. For example. API name—When you created the Merchandise object.Tutorial #1: Creating a Warehouse Application Tell Me More. you didn't specify an API name. Price. If you guessed that custom fields have names that end in __c. Price. price. relationships. the detail page for the custom object opens.

c. a.Tutorial #1: Creating a Warehouse Application a. Click Save & New to save the Description field and return to the first step of the wizard. b. Click Next. 2. For Data Type. accept the defaults. and click Next again. d. b. Create the Price field. It's a good idea to fill these in. Optionally. select Currency. Do not fill in the Default Value field. Click New to launch the New Custom Field wizard. Fill in the custom field details: 8 . Fill in the custom field details. • • • • • For the Field Label. Scroll down to the Custom Fields & Relationships related list. enter Description and press the Tab key. f. One of your business rules says that you can't create new merchandise without providing a description. Select the Required checkbox. Making Description a required field fulfills that business rule. e. and click Next. The Field Name field should already be populated with the field name: Description. fill in the Description and Help Text fields. select Text Area and click Next. For Data Type. but for the sake of brevity we leave these out in the remainder of the workbook.

c. 3. and click Next. For example. You may have noticed that when you enter a Field Label. accept the defaults. The Field Name is used internally in code. the system automatically populates the Field Name as well.. you can make another Stock Price field now if you want to. For Data Type. and click Next. d. a description. In the next step. However. Fill in the custom field details: • • For the Field Label. a field labeled “Customer ph# :” would be named Customer_ph in the code (the system replaces spaces with underscores and removes the # and : characters). At this point we have a nice representation of our warehouse items: they each have a name. and click Next. e. Accept the defaults for the remaining fields. So why do you need both? A Field Label is what the user sees.Tutorial #1: Creating a Warehouse Application • • • For the Field Label. a. e. accept the defaults. Leave the defaults for the remaining fields. c. select Number and click Next. For the Length enter 16 and for Decimal Places enter 2. and must not contain spaces or illegal characters. We've also recorded the total number of items (Total Inventory) that we have for each piece of merchandise. click Save & New to save the Price field and to return to the first step of the wizard. enter Price. enter Total Inventory. In the next step. and click Next. See Also: Tutorial #1: Creating a Warehouse Application Step 1: Create a Merchandise Custom Object Step 3: Create a Tab 9 . and we'll use that for both the stock price and retail price. Check the Required checkbox. b. Select the Required checkbox.. In the next step. d. and so it should be easy to read and may contain spaces. and a price. Create the Total Inventory field. Note: This app has only one Price field. Tell Me More. just follow the same steps above and use the Stock Price name.. Click Save to create the Inventory field and to return to the Merchandise Custom Object page.

As soon as you create the tab. 2. From the Object drop-down list. In the Custom Objects Tabs related list. In this step you will create a tab for the Merchandise custom object. Within the Setup area. See Also: Tutorial #1: Creating a Warehouse Application Step 2: Add Description. 3. 5. select Merchandise. For the Tab Style.. Accept the remaining defaults. 1. Price.. When users click this tab. and Total Inventory Fields Step 4: Create a Warehouse App 10 . Click Next and then Save to finish creating the tab. view. click New to launch the New Custom Tab wizard. you're not stuck with a standard set of icons and colors. and click Next. you can see it at the top of the screen. When you create a tab. they will be able to create. 6. Tell Me More. click the lookup icon and select the Box icon. and edit records. click Create ➤ Tabs. you can choose your own color and custom image by clicking Create your own style.Tutorial #1: Creating a Warehouse Application Step 3: Create a Tab Tabs provide an easy way to find and organize objects and records. 4.

com app menu in the upper right corner of the page. On the Select Type page. Tell Me More. Click Next. For example. Select the Visible checkbox to make the application available to all user profiles. For the App Name. using the default logo for the app. Click Save to create the Warehouse application. 5. Later. 1.. Navigate to Your Name ➤ Setup ➤ Create ➤ Apps. enter Warehouse. 8. Fill in the custom app details. As soon as you create the application. enter Warehouse. and click Next. locate the Merchandise tab and click Add to add it to the list of selected tabs. and click Next.. you'll add more tabs to the app. • • For the App Label. The tabs in an application don't have to be related to each other. you can add that to 11 .Tutorial #1: Creating a Warehouse Application Step 4: Create a Warehouse App An application is a set of tabs. choose Custom app and click Next. 2. 3.. In fact. you can modify custom applications to group all of your most frequently used tabs together in one place. 7. if you refer to the Start Here tab a lot. 4. it appears in the Force. In this step you create a Warehouse application and add a tab to it. Click New to launch the New Custom App wizard. 9. Accept the defaults on the next page. Leave the Default Landing Tab set to the Home tab. 6. 10. In the Available Tabs list.

Click Save. Go ahead and create some more.. In the Price field enter 9. 4. Tell Me More.com.. For Description field enter A small plane. read. Select the Warehouse application from the Force. but it would be more realistic if you had more merchandise. as shown in the following image. 2.99.. Tip: click Clone on this record to create another similar one. See Also: Tutorial #1: Creating a Warehouse Application Step 4: Create a Warehouse App Summary 12 .com app menu. When you define an object on Force. In the Total Inventory field enter 2000.Tutorial #1: Creating a Warehouse Application the Warehouse app. Fill in all the fields. 3. the platform automatically generates a user interface that lets you create. Your warehouse will work just fine with only one product. bought. • • • • In the Merchandise Name field enter Wee Jet. See Also: Tutorial #1: Creating a Warehouse Application Step 3: Create a Tab Step 5: Create a Merchandise Record Step 5: Create a Merchandise Record At this point you've created a functioning application. update. 1. and then use Save and New to create more new records rapidly. You can switch between applications you have created. Now check to see how your new application works. and delete records. Click the Merchandise tab and then click New to create a new product. or installed by simply selecting any one of them from the menu.

and a tab.Tutorial #1: Creating a Warehouse Application Summary Congratulations! You have just built a Warehouse application that keeps track of products you have in stock. it's easy to use the online interface and wizards to create a custom object. it already has a lot of built-in functionality. As you can see. The next step is to use an invoice to track how your merchandise moves in and out of your warehouse. fields. such as the ability to view and create merchandise. See Also: Tutorial #1: Creating a Warehouse Application Step 5: Create a Merchandise Record 13 . and then pull it all together into an application that lets you create and track information about your merchandise. Although the application is far from complete.

you create an invoice statement with a unique number. In the Record Name field . and a description. Prerequisites Warehouse App You first need to create the basic Warehouse application as described in Tutorial #1: Creating a Warehouse Application on page 5. 1. you can think of relationship as foreign keys. Click New Custom Object and fill in the custom object definition.com takes care of the underlying implementation for you. In the Plural Label field. • • • • In the Label field . If you're familiar with relational databases. enter Invoice Number. and all you need to do here is establish how the objects are related. This relationship lets you compose multiple line items and associate them with a single invoice statement. enter Invoice Statements. Click Your Name ➤ Setup ➤ Create ➤ Objects. Select Starts with vowel sound. you create two new objects. so you'll also add a relationship between the merchandise and line item objects. an invoice statement and a line item. a status. Duration: 20-30 minutes In this tutorial.Tutorial #2: Adding Relationships Tutorial #2: Adding Relationships Level: Beginner. and associate them to each other in a master-detail relationship. In this step. Each line item is an indication of how many units of a particular merchandise item was sold. the difference being that Force. enter Invoice Statement. 14 . 2. See Also: Step 1: Create an Invoice Statement Custom Object Step 2: Create a Line Item Object Step 3: Relate the Objects Step 4: Add Invoice Statements to the App Step 5: Create an Invoice Record Summary Step 1: Create an Invoice Statement Custom Object An invoice statement is required to move inventory into or out of the warehouse.

4.Tutorial #2: Adding Relationships • • • In the Data Type field . enter INV-{0000}. In the Optional Features section. select Auto Number. In the Starting Number field. In the Display Format field. each entry on its own line.. Fill in the custom field details. c. • • In the Field Label field . 3. select Picklist and click Next. Enter the following picklist values in the box provided. Scroll down to the Custom Fields & Relationships related list and click New. 15 . Add a Status field. b. enter Status. select Allow Reports and click Save. For Data Type. enter 1. Open Closed Negotiating Pending • Select the checkbox for Use first value as default value. a.

The platform will now automatically assign a number to each new unique record that is created. a. Tell Me More. Click Save to the detail page for the Invoice Statement object. select Read Only and then click Next.. enter Description. and click Next again. Now create an optional Description field. See Also: Tutorial #2: Adding Relationships Step 2: Create a Line Item Object 16 . In the Data Type field. When displayed.. Your Invoice Statement object should now have two custom fields. e. Click Next. accept the defaults. Note how we set the invoice name data type to Auto-Number. the format will look as follows: INV-0002. c. Click Save & New. beginning with the starting number you specify. In the Field Label and Field Name fields.Tutorial #2: Adding Relationships d. and also supplied a Display Format. f. select Text Area and click Next. as shown here. For Field Level Security. 5. b. Click Next. d..

enter 16.Tutorial #2: Adding Relationships Step 2: Create a Line Item Object Each invoice is going to be made up of a number of invoice line items. Leave the Data Type field set to Text. e. • • In the Field Label field. enter Unit Price. select Allow Reports and click Save. Add a read-only Unit Price field. 1. a. d. which represent the number of Merchandise items being sold at a particular price. enter Line Items. Click New Custom Object and fill in the custom object definition. Scroll down to the Custom Fields & Relationships related list and click New. • • • • In the Label field . You are first going to create the Line Item object. In the Length field. click Next. and then click Save & New. and for Decimal Places enter 2. Fill in the custom field details. and then later relate it to the Invoice Statement and Merchandise objects. Click Your Name ➤ Setup ➤ Create ➤ Objects. In the Data Type field. select Currency and click Next. Select Read-Only for all profiles. In the Optional Features section. In the Plural Label field . The field is read-only because the value will be retrieved from the Merchandise object in a later tutorial. enter Line Item. 17 . Change the Record Name to Line Item Number. We'll call it Unit Price so that we don't get confused with the Merchandise object Price field. Click Next. 2. 4. b. 3. c.

8. accepting the defaults.. You follow similar steps to add a Units Sold field. On the detail page of the Line Item object. 4. In the Data Type field. Click Save to return to the detail page of the Line Item custom object. 5. these get their values from other objects. In the Related To field. which defaults to Open. In the Field Label field. In the Data Type field. 9. scroll down to the Custom Fields & Relationships related list and click New. You also created two custom fields that have system-generated values: the Status picklist. d.. Click Save & New. Unlike the previous fields. 1. Inventory Statement. Accept the defaults on the following screens by clicking Next. select Master-Detail Relationship and click Next. Tell Me More. you probably selected Required by mistake.. Deselect the checkbox next to Merchandise Layout so that Line Items don't appear on the Merchandise related list. b. Click Next. numbers. In the next step you will create two more fields. and the Invoice_Number field. 5. and then click Save to return to the Inventory Item detail screen. 2. In the Related To field. The Line Item is related to both an Invoice Statement (a statement is composed of a number of line items) and Merchandise (a line item takes its price from the merchandise). select Master-Detail Relationship and click Next. Accept the defaults on the next three screens by clicking Next. All of those fields have something in common: the values are provided by the user. At this point you've created three custom objects: Merchandise. select your Invoice Statement custom object and click Next. which is automatically assigned by the Auto-number data type. and Line Item. 6. and currency. In the Data Type field. 18 . 7. c.Tutorial #2: Adding Relationships Note: If Read-Only is not available. Click Previous and deselect Required. a. 3. you want to relate them to each other. enter Units Sold and click Next. select Number and click Next. See Also: Tutorial #2: Adding Relationships Step 1: Create an Invoice Statement Custom Object Step 3: Relate the Objects Step 3: Relate the Objects Now that you have all the objects representing the data model. On each of those objects you created custom fields to represent text. select your Merchandise custom object and click Next.

Within the Setup area. click the lookup button and select the Form icon. From the Object drop-down list. On the Add to Custom Apps page.. so that you can view. and update records.Tutorial #2: Adding Relationships Tell Me More. for the Merchandise custom object. 4. Because you also related the objects. In the Custom Object Tabs related list. This will expose the user interface that Force.. You have just created two master-detail relationships ensuring that your Invoice Statement records are related to Invoice Line Item records. click New to launch the New Custom Tab wizard. Accept the remaining defaults. edit. Master-detail relationships also support roll-up summary fields. delete. click Create ➤ Tabs.com automatically generates for this object. Click Save to finish creating the tab. deselect all the checkboxes except Warehouse. Click the Invoice Statements tab.. 1. 7. you'll want to create a tab for the Invoice Statement object and add it to your Warehouse app. See Also: Tutorial #2: Adding Relationships Step 2: Create a Line Item Object Step 4: Add Invoice Statements to the App Step 4: Add Invoice Statements to the App Just as you did before. 6. 3. Click New. 19 . This will add the Invoice Statements tab to your Warehouse app. the platform automatically generates a user interface for the objects you create. 2. 5. Your Invoice Statements tab is now part of your app. 1. You'll use that feature in a later tutorial. 2. and that the Invoice Line Items are related to Merchandise. See Also: Tutorial #2: Adding Relationships Step 3: Relate the Objects Step 5: Create an Invoice Record Step 5: Create an Invoice Record As you saw in the previous tutorial. select Invoice Statement. and click Next and then Next again. the user interface provides a way of navigating between related records as well. For the Tab Style. allowing you to aggregate information about the child records.

. In the Unit Price field enter 10. like Invoice Statements? The short answer is that it's easier to work with text when 20 . 2. and how the user interface displays an empty Line Items related list below it. 3. In the Units Sold field. You might be wondering why Line Item Number is a text field. enter 4. enter First Invoice and then click Save. Click New Line Item.Tutorial #2: Adding Relationships 3. 1. For the Merchandise field.. why not make it an auto-number field. In the Description field. The detail page of your invoice statement should look like this. Fill in the fields. Notice how the invoice was automatically assigned a number. If line items are numbered. Click Save. • • • • In the Line Item Number field enter 1. when what you enter is a number. The Invoice Statement is linked to the Line Item via a master-detail field—that's how you created this relationship and why there's a related list on the Invoice Statement detail page. Next you'll add a line item to the invoice.. Tell Me More. click the lookup button and select a product.

The relationships work like foreign keys in relational databases. but it makes a later tutorial. yet they operate at a more abstract level. See Also: Tutorial #2: Adding Relationships Step 5: Create an Invoice Record 21 . and in the next tutorial you'll see how to sum the price of each invoice line item into the invoice statement. You can make Line Item an auto number field if you want to. Tutorial #10: Creating a Public Web Page Using Sites. you created relationships between the objects in your data model. a bit more difficult. See Also: Tutorial #2: Adding Relationships Step 4: Add Invoice Statements to the App Summary Summary In this tutorial. and this tutorial is supposed to be easy. letting you concentrate on what matters (the relationships) instead of the underlying implementation. Now that you have built the basic application. you can add business logic with formulas and validation rules in Tutorial #3: Using Formulas and Validation Rules on page 22.Tutorial #2: Adding Relationships we work with records. The master-detail relationship allows you to aggregate information. You'll learn about that later as well. The relationships also provide additional benefits: you can navigate to the related records in a user interface and a query language.

3. validate your data. You will also use this new line item value and a property of the master-detail relationships to automatically total an invoice value. and click New. Scroll down to the Custom Fields & Relationships related list. you will add a new calculated field called Value to the line item. ensuring that you can't create a line item for more merchandise than you have in stock.Tutorial #3: Using Formulas and Validation Rules Tutorial #3: Using Formulas and Validation Rules Level: Beginner. with formula fields and validation rules. you will add a formula to perform an inventory check. Both formula fields and field validation rules use built-in functions that allow you to automatically manipulate your data. 1. Choose Formula as the field type. you will enhance the Warehouse app by adding a formula field to automatically calculate the total value for each line item. and calculate other values based on your data. and return a result. See Also: Step 1: Calculate a Value for Each Line Item Step 2: Calculate a Value for the Invoice Statement With a Roll-Up Summary Field Step 3: Check Inventory With a Validation Rule Step 4: Test the Validation Rule Step 5: Improve the Validation Rule Summary Step 1: Calculate a Value for Each Line Item In the first step of this tutorial. and click Next. Finally. Navigate to the Line Item custom object page by clicking Your Name ➤ Setup ➤ Create ➤ Objects ➤ Line Item. you reference fields in your app's records. where you can reference values in other cells of the spreadsheet. Duration: 20-30 minutes The Force. Prerequisites Warehouse App You first need to create the basic Warehouse application and add relationships. as described in Tutorial #2: Adding Relationships on page 14. perform calculations. This field will multiply the number of items with the price and act as a total for each line item. 22 . In this tutorial.com platform lets you create formulas and field validation rules to help maintain and enhance the quality of the data entered in your app. 2. However. The functions you use in formula fields and field validation rules are a lot like the functions you would use in a spreadsheet program.

You should now see Unit_Price__c in the text box. and then click Save. Roll-up summary is a special type of field that lets you aggregate information about related detail (child) objects.Tutorial #3: Using Formulas and Validation Rules 4. When you return to the detail page for the custom object. select Units Sold.. 5. You should now see Unit_Price__c * Units_Sold__c in the text box. 2.. 1. choose Currency. 3. you can see there's a new field called Value. There's also an Advanced Formula tab. click Next again. it makes sense to add them all to get the invoice total. you want to sum the value of each line item. 10. Click Next. enter Value. and click Next. as you have done here. 23 . Click Next. The formula you entered was quite straight forward: a simple multiplication of two field values on the same record. In the Formula Return Type field. Navigate back to the Invoice Statement custom object page by clicking Your Name ➤ Setup ➤ Create ➤ Objects ➤ Invoice Statement. Tell Me More. In the Insert Merge Field drop-down list. In the Field Label and Field Name fields. which allows you to do much more with these formulas. 7. The Formula field type is great for automatically deriving field values from other values. Click the Insert Operator drop-down list and choose Multiply. 9. we can use a roll-up summary field to calculate this value. In this case. and click New. 6. In the Insert Merge Field drop-down list. Choose Roll-Up Summary as the data type.. Because the line items have a master-detail relationship with the invoice statement. select Unit_Price. Scroll down to the Custom Fields & Relationships related list. See Also: Tutorial #3: Using Formulas and Validation Rules Step 2: Calculate a Value for the Invoice Statement With a Roll-Up Summary Field Step 2: Calculate a Value for the Invoice Statement With a Roll-Up Summary Field Now that you have the total for each line item. 8.

5. In the Field to Aggregate list choose Value.Tutorial #3: Using Formulas and Validation Rules 4. written in the same formula language that you used to create the formula field. 6. 7. If the field shows an hour glass. choose Sum. Tell Me More. displaying the total value of all the invoice line items. You can test this new functionality by adding a new line item. 1. Verify that your screen looks like the following and then click Next. See Also: Tutorial #3: Using Formulas and Validation Rules Step 1: Calculate a Value for Each Line Item Step 3: Check Inventory With a Validation Rule Step 3: Check Inventory With a Validation Rule The fields that you define in objects can have validation rules. Scroll down to the Validation Rules related list. 9. 8. and to display a message to the user if a field value is not valid. Navigate back to the Line Item custom object page by clicking Your Name ➤ Setup ➤ Create ➤ Objects ➤ Line Item. The error condition formulas should evaluate to true when you want to display a message to the user. and click New. In the Summarized Object list choose Line Items. 2. For Roll Up Type field. enter Invoice Value and click Next. Click Next again and then click Save. wait a few seconds and then refresh. 24 . In the Field Label field. If you navigate back to an invoice statement record.. you'll see your new roll-up summary field in action. The validation rules can be used to determine what range of input is valid...

You can enter a formula directly into the Error Condition Formula area. In the Error Condition Formula area. Select Line Item > in the first column.Total_Inventory__c < f. In the Rule Name field. Select Total Inventory in the third column. but as you saw here. 6. Tell Me More. Click Check Syntax to make sure there are no errors. you can easily traverse the available objects and find the components you need for the formula. 7. Click Insert and verify the code looks like the following. Select Line Item > in the first column. enter Order in stock. enter You have ordered more items than we have in stock.. Merchandise__r. then choose Units Sold from the drop-down list. Click Save. click Insert Field to open the Insert Field popup window. Select Units Sold in the second column. Click Insert. 8.Total_Inventory__c < Units_Sold__c 5. 25 . In the Error Message field. d. fix them before proceeding. If you do find errors. i. Type the less-than symbol < so that the formula looks like this: Merchandise__r. g.. a. e. select Field. 4. b. Let's analyze the formula you created.Tutorial #3: Using Formulas and Validation Rules 3. h. c. Select Merchandise > in the second column.. For the Error Location. Click Insert Field again.

Scroll down to Line Items and click Edit next to one of the line items. you need to provide a formula that is true if an error should be displayed. Click Cancel. Click Save. Click on the Invoice Statements tab and select an existing invoice. the formula checks that the total inventory on the related merchandise record is less than the number of units being sold. You should see an error indicating that there are not enough items in stock.Total_Inventory__c—This tells the system to retrieve the value of Total Inventory field on the related Merchandise record. • • • Total_Inventory__c—This is the field you created to track the total amount of stock on a Merchandise record. Putting it all together. See Also: Tutorial #3: Using Formulas and Validation Rules Step 3: Check Inventory With a Validation Rule Step 5: Improve the Validation Rule 26 . Units_Sold__c—This refers to the Units Sold field on the current (Line Item) record.Tutorial #3: Using Formulas and Validation Rules • Mechandise__r—Because the Merchandise object is related to the Line Item object. 2. Merchandise__r. 3. See Also: Tutorial #3: Using Formulas and Validation Rules Step 2: Calculate a Value for the Invoice Statement With a Roll-Up Summary Field Step 4: Test the Validation Rule Step 4: Test the Validation Rule Now test the validation rule you created in Step 3. 4. that's what the Mechandise__r is doing. Modify the Units Sold value to a number larger than the amount in stock. Click Cancel. 5. the platform automatically provides a relationship field that lets you navigate from a Line Item record to a Merchandise record. 1. and this is just what you want: it will only be true when the total inventory is less than the units sold. As indicated on the Error Condition Formula page.

Click Check Syntax to make sure there are no errors. false otherwise. IF ( Units_Sold__c < PRIORVALUE(Units_Sold__c). and next to Order in stock click Edit. Since you have enough stock. then you simply check inventory as you did previously. you'll need to use the PRIORVALUE() function to tell you the prior value of the field before it was modified. For new records. Merchandise__r. Navigate back to the Line Item custom object page by clicking Your Name ➤ Setup ➤ Create ➤ Objects ➤ Line Item. ISNEW is the condition.Total_Inventory__c < (Units_Sold__c . IF( ISNEW(). you should only need to verify that the number of additional items is in stock. If ISNEW is true. See Also: Tutorial #3: Using Formulas and Validation Rules Step 4: Test the Validation Rule Summary 27 .PRIORVALUE(Units_Sold__c)) ) ) 4.Total_Inventory__c < Units_Sold__c . Replace the existing formula with the following. you know that you're performing an update to an existing record. If the prior value was greater. then you've increased the number of units. You can improve the validation rule to include these scenarios by using the ISNEW() function in your formula. If ISNEW is false. Or if you increased the number of units sold. this time to determine if the number of units has gone up or down. 2. not creating a new record. so you perform another conditional check. Scroll down to the Validation Rules related list.. Click Save. which determines whether you are creating a new record.Tutorial #3: Using Formulas and Validation Rules Step 5: Improve the Validation Rule The logic in the validation formula is a little bit flawed! Imagine that you edit a record and decrease the number of units sold. 1. • • • • IF is a conditional. In this case.. If the prior value was smaller. 3. Tell Me More. by comparing it to its prior value using the PRIORVALUE function. Let's look at this formula in a little more detail. then you've updated the record and decreased its units. so you have to check whether there's enough inventory to hold the difference between the new number of units and the old. ensuring that at run time one of the two branches will be taken depending on the condition. 5. you shouldn't need to check inventory. Merchandise__r. If it's not a new record. This function returns true if you're creating a new record. you need to check that you have • • not sold more than you have in stock. FALSE. you return FALSE to indicate that there's no validation failure..

but you enhanced it to work with both new records. An invoice could be made up of multiple line items. so you created a roll-up summary field to automatically add up the line item subtotals.Tutorial #3: Using Formulas and Validation Rules Summary In this tutorial you created formula fields and validation rules that enhance and validate your app's data. The first version of the rule was simple. These kinds of modifications can be applied to any field in your app when you want to make sure the data entered meets certain criteria. and existing records with updates. You also learned how to define a validation rule to make sure you have enough items in stock. See Also: Tutorial #3: Using Formulas and Validation Rules Step 5: Improve the Validation Rule 28 . For the first formula you created a subtotal for each line item by multiplying the price of a product by the number of units that were ordered.

The Dashboards tab shows data from charts.com provides a drag-and-drop report builder that lets you quickly organize and present your data. select Reports. 1. like sum. and the reports in folders that you can access. It's easy to group and summarize your data. 4. then click the Add arrow. 3. Click Edit. Select Warehouse from the Apps list. Click Your Name ➤ Setup ➤ Create ➤ Apps. Click Save. Duration: 20-30 minutes You’ve built an application that captures and manipulates warehouse data. lists your data in a simple table. maximum. and add formulas and charts. tabular. enter Merchandise Reports. Step 2: Create a Tabular Report In this step you will create a tabular report. Click the Reports tab.. • • The Reports tab provides access to a set of pre-defined reports. Click Create New Folder. 2. Step 1: Add Reports and Dashboards to the Warehouse App Add the Reports and Dashboards tabs to your Warehouse app so you can easily access them later.. 5. The first format. but can be used to show column summaries. Dashboards provide a snapshot of key metrics and performance indicators for your organization. tables. and another invoice. In this tutorial. Go ahead and create one or two more merchandise items. average.. In Report Folder Label. then add relationships as described in Tutorial #2: Adding Relationships on page 14 and add workflow as described in Tutorial #5: Automating Processes Using Workflow on page 38. Prerequisites Warehouse App First create the basic Warehouse application in Tutorial #1 on page 5. 3. Tell Me More. They don't contain groupings. You will also create a dashboard using one of your reports. all of the reports that you create. gauges. Tabular reports present data in simple rows and columns. You can then share these reports to help business users make more informed decisions. much like a spreadsheet. but you want to report on that data as well. Force. Data The reports you create in this tutorial will look better if you have more data. 4.Tutorial #4: Creating Reports and Dashboards Tutorial #4: Creating Reports and Dashboards Level: Beginner. Click Save. you will display your data in reports using three different formats. or Visualforce pages. 1. metrics. Repeat for Dashboards. and minimum. 29 . 2. In the Available Tabs panel. The next two let you group your data and add a chart.

Select Sum. Figure 1: Report Builder 8. but let’s add a few bells and whistles like sums and averages. placing them beside the Merchandise Name column. press CTRL (Windows) or Command (Mac). Select Max and Min. The report builder appears. Click next to Price header and select Summarize this Field. Click Apply. In the Select Report Type panel. 1. Click Create New Custom Report.Tutorial #4: Creating Reports and Dashboards 5. 30 . 3. based on object relationships. 7. select Merchandise and click Create. 6. 4. They also determine which fields you can use. with its dynamic preview built from a limited number of records. select Other Reports. The default report format is tabular. 2. Click next to Total Inventory and select Summarize this Field. In the Select Category panel. 5. Drag each of the following fields from the Fields pane to the Preview pane. Report types set the rules for which records to show in reports. • • • Description Price Total Inventory You now have a basic report. To select multiple fields or columns. The Merchandise Name field is in the report by default.

within the Line Item folder. optionally added summary data.. Tell Me More. with the addition of grouping and charts. 8. Select Merchandise Reports from the Report Folder drop-down list. selecting the Merchandise Reports folder. Click Save and Return to Report. 2. You can click through to the data records that are being reported on. select the Unit Price field. and set data filters for the report. The folder a report is placed in determines its visibility and security. In the Report Name field. 10. You can group report data by up to three levels and add a chart. A green line will appear when you can drop the field to create a new column. you can add Public Groups. 3. and clicking Go. From the Fields pane on the left. 12..com. • • • Step 3: Create a Summary Report Summary reports allow for more advanced customization than tabular reports. 4. For example. click the name of any merchandise record listed in the report to view its detail page. a characteristic found in all reports on Force. then Invoice Statements with Line Items and Merchandise.. selected the report format. While you are not able to specify a specific user to access a report folder. Click Tabular Format and choose Summary instead. • You can order the report data by clicking the column headers to toggle between ascending and descending order. 31 . Click Create New Custom Report. 5. 7. In this step you'll create a summary report and group by the merchandise name. In the Filters pane. Review the data and click Save As. Roles. but we want a summary report. Click Run Report. or Roles and Subordinates to control visibility. drag it to the Preview pane. Click Create. 9. Click the Reports tab. The procedures you followed in creating this report will be similar to those you follow in the later steps. determined which fields to display. select All Merchandise from the View drop-down list to assign the set of records that the report will use. enter All Merchandise with Price and Inventory. You selected the objects that you want to report on. Modify these settings by clicking Edit on the Report Folder on the Reports tab.Tutorial #4: Creating Reports and Dashboards 6. 1. and drop it on the right of Merchandise Name. The default format is tabular. The Grand Totals area of the report indicates the record count as well as the summaries you chose. Click Apply. You can return to your reports at any time by selecting the Reports tab. 11. You can make additional changes to this report by clicking Customize. You will now see your All Merchandise with Price and Inventory report displayed. The other reports in this tutorial follow similar instructions. 6. Select Other Reports.

select Merchandise Reports. In the Preview pane. 7. Select Plot additional values. drag it to the Preview pane. 5. click the down arrow next to the field name and choose Remove Group. In the Value drop-down list. select Sum of Units Sold. Click the down arrow next to Unit Price. Click the down arrow next to Units Sold. and then click Apply 10. within the Line Item folder. 3. select Merchandise: Merchandise Name. chooseSum. 10. enter Merchandise Sold by Invoice No & Price. and then click Apply 8. select the Units Sold field. Figure 2: Invoice Report with Bells and Whistles Now let's add a fancy combination chart to the report: 1. Click the vertical bar chart. 11. click Add Chart to create a chart to represent your data. In the Report Folder drop-down list. select Average of Unit Price. This aggregates data by the unique merchandise item. The report now includes all the invoices and their associated line items grouped by merchandise item. Click OK. 9. In the Report Name field. The Chart Editor dialog box appears. choose Average.Tutorial #4: Creating Reports and Dashboards Caution: If you drop Unit Price or Units Sold into a grouping by mistake. 4. Click Save and Run Report. Click Save. select Summarize this Field. Select the Merchandise Name field (either from Fields or Preview panel) and drag it to the area labeled Drop a field here to create a grouping. In the Y-Axis drop-down list. 2. enter What merchandise has been selling and what’s the average unit price? 13. In the Report Description field. 6. 14. which is located just above the grouping zone. In the Display drop-down list. and drop it on the right of Unit Price. Again in the Fields pane on the left. 9. 8. 12. select Line. 32 . select Summarize this Field. as well as average price and total units sold. You need to drop the field into a column. Select Use second axis. 7. In the X-Axis drop-down list.

In the Preview panel. Select the Sum checkbox. 2.. To add a summary. 10. Double-click Invoice Statement: Invoice Value to add it to the report. You can check rows of interest on your report and click Drill Down to filter the report to only those rows. In the Filters pane. Click Create New Custom Report.Tutorial #4: Creating Reports and Dashboards The combination chart shows the data. click Tabular Format and choose Matrix from the drop-down list. 1. 8. then Merchandise with Line Items and Invoice Statements. Double-click Line Item: # Units Sold to add it to the report. 7. 12. Click the Reports tab. click next to Invoice Statement: Invoice Value and select Summarize this Field. Double-click Merchandise: Merchandise Name to add it to the report. Clear the slate by selecting Remove all Columns and then OK in the popup. 9. Select the Sum checkbox. To add a summary. 5.. Create a column grouping for the status of invoice statements by dragging the Invoice Statement: Status field to the column drop zone. 13. This report will show summary data of merchandise items per day and across different invoice statement status values.. Step 4: Create a Matrix Report In this step you will create a matrix report that groups and summarizes both columns and rows. plotting each merchandise item against units sold (across all invoices) as well as superimposing a second graph mapping the average unit price for the item. Click Create. 3. Select Other Reports. 4. Create a row grouping by dragging the Invoice Statement: Create Date field to the row drop zone. 33 . ensure that All Merchandise is selected from the View drop-down list. 11. Create a secondary row grouping by dragging the Merchandise: Merchandise Name field to the second drop zone. 6. click next to Units Sold and select Summarize this Field. Tell Me More.

Click Save.Tutorial #4: Creating Reports and Dashboards 14. select Merchandise Reports. 9. and within the report. 34 . 5. 6. You’ll get an astounding amount of information generated in the report. 13. 8. 4. For Chart Title. and automatically takes into account the status of each invoice. Select Use second axis. Select the Stacked graph type. Select Plot additional values. In the Group-By drop-down list. In the X-Axis drop-down list. 2. enter Units Sold per Day by Invoice Status. 14. Select the Vertical Bar Chart. 20. Click Customize. 7. 15. In the Y-Axis drop-down list. 11. For Legend Position. enter Daily Units Sold by Invoice Status. depending on the column (Invoice Status) and row groupings (Created Date and Merchandise Name). select Invoice Statement: Status. 18. Click the Formatting tab to further customize the chart. grouping the invoices over daily periods. then press the TAB key. 17. select Sum of Units Sold. 12. For Report Name. For Value. Click Add Chart. select Bottom. For Report Description. select Record Count 10. Click Run Report. by Invoice Status? 19. select Invoice Statement: Created Date. Values are tallied both horizontally and vertically. Select Show Axis Label. Click OK 16. Figure 3: Matrix Table Now let's add a combination chart to this report: 1. For Report Folder. Click Save and Run Report. enter How many units are we selling each day. The resulting graph summarizes the units sold. 3. The Chart Editor dialog box appears.

. you’ll see multiple summary rows. select Merchandise Dashboards. Click the arrow icon in the Folders area on the left side of the page. then click New Dashboard Folder. metrics. 35 . Your data can be represented by charts. and press the TAB key. Click Dashboard Properties. • • The Sum of Units Sold has a scale on the left side of the chart that correlates to the columns of your chart. • • • Step 5: Create a Dashboard You can show all the reports you've built in the same place by including them in a dashboard. and even Visualforce components. 1. Click the Dashboards tab. tables. Choose either a predefined duration or enter your own custom dates and click Run Report to update the page. 9. Similar to reports..Tutorial #4: Creating Reports and Dashboards Tell Me More. For Title. Click OK. gauges. If you want to narrow the time frame that is represented. In the Save To drop-down list. Record Count has its own scale on the right side of the chart that correlates to the blue line on your chart. making your report easier to see. as you see in Invoice Statement: Status. Click New Dashboard. you can define it in the upper right corner of the page. You can quickly change how your chart is displayed by clicking Edit. dashboards are organized into folders. 4. Click Go to Dashboard List to view your dashboards. 8. 2. 10. which provides a graphical summary of the data in your application. Because you defined multiple grouping levels in the report. 7. enter Merchandise and Invoice Summary. 3.. 5. For Dashboard Folder Label. 6. Click Save. enter Merchandise Dashboards. The chart and report currently display all records. regardless of when they were created. You can deselect Show ➤ Details to only show summary information.

Your dashboard now has one component in the left column. • When you set a running user for a dashboard. click next to the View dashboard as field. then Edit again.. Click Edit. To set the running user. and can be delivered through email. On the Vertical Bar Chart. click Reports. You can add up to 20 components to create a more complex dashboard. Click OK. From the Data Sources tab. click + next to Merchandise Reports. and drag Weekly Units Sold by Invoice Status on top of the vertical chart in the first column. specific user. Each time you view a dashboard. 16. Select your Home tab to see it in action. Dashboards can be updated either manually or on a schedule. • • • 36 . drag the vertical bar chart to the first column. Add the dashboard to your Home tab by clicking Setup ➤ Customize ➤ Home ➤ Home Page Layouts. it runs using the security settings of that single. A dashboard won't automatically refresh unless it is set to do so. Add a header to the component by clicking Edit Header and entering Items Sold per Day. All users with access to the dashboard see the same data.Tutorial #4: Creating Reports and Dashboards 11. it indicates in the upper right corner when it was last refreshed. 14. click . Tell Me More. 13. 12. Click Next. regardless of their own personal security settings.. and select the Dashboard Snapshot checkbox. Select Use chart as defined in source report. then Save and Run Dashboard. 17. click Refresh. then Save. From the Components tab.. To refresh the data in the dashboard. 15. Click Save.

and charts. Creating meaningful reports is a skill well worth learning! 37 . which you can place on your Home tab for quick reference. and a matrix report that provided a multi-dimensional analysis of your data. You also created a dashboard.Tutorial #4: Creating Reports and Dashboards Summary In this tutorial you created three reports: a quick tabular report that listed your records with simple column summaries. a summary report that grouped and graphed your data. experiment with them by modifying the filters. Now that you’ve built the basic reports. groupings.

3. Workflow rules can trigger actions (such as email alerts. See Also: Step 1: Populate the Line Item Price Using a Workflow Rule Step 2: Update Total Inventory When an Order is Placed Step 3: Test the Workflow Rules Summary Step 1: Populate the Line Item Price Using a Workflow Rule At this point. click New Rule. In the Rule Criteria field. you've created the Line Item and the Merchandise objects with Price fields. 5. you can use workflow rules to automate your procedures and processes. 38 . In your Force. In Step 1 of the Workflow Rule wizard. Now you'll create a workflow rule to populate the unit price on the line with the unit price on the merchandise at the time the line item is created. tasks. criteria. You can create this complex logic quite easily with a declarative workflow rule. select formula evaluates to true. and the second updates the inventory whenever you update a product line item. who has access to all data. On the All Workflow Rules page. though you probably didn't notice that in the user interface because your default user is an administrative user. Duration: 20–25 minutes Your company can operate more efficiently with standardized internal procedures and automated business processes. and outbound messages) based on time triggers. enter Line Item Created. You've also marked the Line Item Price field as read-only. field updates. In the Rule Name field. click Continue. Prerequisites Formulas and Validation You first need to create the roll-up summary field and validation rules as described in Tutorial #3: Using Formulas and Validation Rules on page 22. 2.com app. 1.Tutorial #5: Automating Processes Using Workflow Tutorial #5: Automating Processes Using Workflow Level: Intermediate. For Evaluation Criteria. If you see the Understanding Workflow page. select Only when a record is created. 4. and formulas. 6. Click Your Name ➤ Setup ➤ Create ➤ Workflow & Approvals ➤ Workflow Rules. select Line Item as the object and click Next. you create and test two workflow rules. In this tutorial. The first carries the current price of a merchandise item into the newly created line item record.

Tutorial #5: Automating Processes Using Workflow 7. enter Insert Merchandise Price. and Price in the third column. Merchandise > in the second column. In the text box. 39 . Click Insert. Select Use a formula to set the new value. 14. Click Show Formula Editor. click Add Workflow Action and choose New Field Update. enter true. 8. select Line Item in the first box and Unit Price in the second. In Step 3 of the Workflow Rule wizard. 12. The New Field Update wizard opens. Click Insert Field. 10. in the Immediate Workflow Actions section. 15. 16. In the Field to Update drop-down list. 13. 9. 11. In the Name field. Make sure your page looks like the following and then click Save & Next. Select Line Item > in the first column.

click Activate. If your rule is not active. you will see that line item's unit price will automatically be set to the price of the related merchandise record. its criteria are not evaluated when records are created or saved. Remember that because you are an administrator. it just wasn't necessary this time.Tutorial #5: Automating Processes Using Workflow 17. the customer would appreciate being updated with the new price. Tell Me More. You can also use a formula to evaluate an expression. save it. 18. and then view it. click Done. Important: Forgetting to activate a new workflow rule is a common mistake. if the item's price goes down. Click Save to close the New Field Update wizard and return to Step 3 of the Workflow wizard. you see an input field for price.. The reason is that we want the field update to happen every time a record is created. But your users won't see that field because it was set to read-only. If you now create a new line item. The reason this workflow rule runs only when a record is created (and never afterward) is that we don't want to increase the invoice price of an item after the item has been added to the invoice. On the Specify Workflow Actions page. and that's always true. On the Workflow Rule page. It would confuse a customer to suddenly find out the item's price is higher than what was advertised. You might be wondering why we've created a rule whose formula always evaluates to true. See Also: Tutorial #5: Automating Processes Using Workflow Step 2: Update Total Inventory When an Order is Placed 40 .. 19. You'll make that happen later.. However.

On the All Workflow Rules page. In the Field drop-down list. 4. 6.Tutorial #5: Automating Processes Using Workflow Step 2: Update Total Inventory When an Order is Placed Ideally. 11. select Merchandise. Click Your Name ➤ Setup ➤ Create ➤ Workflow & Approvals ➤ Workflow Rules. select Line Item as the object and click Next. In Step 3 of the Workflow Rule wizard. In the second. If you're creating a new line item. The only trick to it is changing the total inventory value. 1. select Invoice Statement: Status. Click Show Formula Editor. otherwise proceed to the next step. If you see the Understanding Workflow screen. This can be accomplished with another workflow rule. enter Line Item Updated. Enter the following code. you want the total inventory of the Merchandise records to be automatically maintained. Select Use a formula to set the new value. Under Value click the lookup icon and choose Open. 5. 15. 7. IF ( ISNEW(). 3. enter Update Stock Inventory. 2. In the first Field to Update drop-down list. 8. Make sure your screen looks like the following and then click Save & Next. The New Field Update wizard opens. As you create new invoices (which will default to "Open" status). In the Rule Name field. you need to decrease the total inventory by the number of units sold. 12. 41 . Click Insert Selected. Then for Operator. click New Rule. 10. But if you're updating a line item. select criteria are met. 13. you want any updates to the line items to be reflected in the Total Inventory field you created on the Merchandise object. select Total Inventory. in the Immediate Workflow Actions section. For Evaluation Criteria select Every time a record is created or edited. In Step 1 of the Workflow Rule wizard. select equals. you need to adjust the total inventory by the difference between the numbers of old and new units sold. click Continue. click Add Workflow Action and choose New Field Update. 9. In the Name field. 14. In the Rule Criteria field.

Click Save to close the New Field Update wizard and return to Step 3 of the Workflow wizard. Then verify that its unit price is automatically set and that the total inventory on the stock has decreased. 2. See Also: Tutorial #5: Automating Processes Using Workflow Step 1: Populate the Line Item Price Using a Workflow Rule Step 3: Test the Workflow Rules Step 3: Test the Workflow Rules You can check to make sure your workflows are functioning as expected by creating a new line item. Click the Invoice Statements tab.Total_Inventory__c . 42 .Tutorial #5: Automating Processes Using Workflow Merchandise__r.Units_Sold__c . click Activate. 17. Set Units Sold to 1000. 1. Merchandise__r. 19. On the Specify Workflow Actions page. Leave the Unit Price field blank.PRIORVALUE(Units_Sold__c)) ) 16. Click the invoice record you created earlier. Select New Line Item and enter the following values.(Units_Sold__c . • • • In the Line Item Number field enter 2. click Done.Total_Inventory__c . Click Check Syntax and make corrections if necessary. 18. 3. On the Workflow Rule page.

click the lookup icon and select the Wee Jet merchandise record. See Also: Tutorial #5: Automating Processes Using Workflow Step 3: Test the Workflow Rules 43 . 5. Now open the Wee Jet merchandise record by clicking on the Wee Jet link. Click Save. The workflow rule automatically updates price and inventory across different objects. 4. The approval process runs whenever a condition is met. and then sends an email alert to the designated recipient. Note that the unit price has been set to the same value as on the Wee Jet record. Notice that the Total Inventory is down to 1000 from 2000 (or whatever you entered). See Also: Tutorial #5: Automating Processes Using Workflow Step 2: Update Total Inventory When an Order is Placed Summary Summary Workflow rules and approval processes help you automate your business processes and enforce your standards. 6. Click line item 2.Tutorial #5: Automating Processes Using Workflow • Next to the Merchandise field.

so that a user sees only his or her records or those of his or her manager. On the All Users page. it's automatically enabled to allow multiple users to log in.com app. In your Force. 44 .Tutorial #6: Creating an Approval Process Tutorial #6: Creating an Approval Process Level: Intermediate. 2. Now you can customize the application by configuring it to function differently depending on the profile of the user logging in. In this tutorial. you create an approval process that requires explicit approval from the manager if an invoice is over $2000. Click Your Name ➤ Setup ➤ Manage Users ➤ Users. In this step. you create a new user and link that user to your current user's account via the Manager field. you can grant read-only access to fields to a certain group of users. click New User. 1. enter Bob. you can use approval processes to enforce consistency and compliance within your company's business practices. Duration: 20–25 minutes Your company can operate more efficiently with standardized internal procedures. Prerequisites Formulas and Validation You first need to create the roll-up summary field and validation rules as described in Tutorial #3: Using Formulas and Validation Rules on page 22. You can also strictly enforce data sharing. Approval processes can automate all of your organization's approvals—from simple to complex. For example. You use this configuration to make sure that if the new user creates an invoice that meets certain conditions.com application. Enter the following information: • In the First Name field. the invoice is routed to his or her manager. 3. or make them completely invisible. See Also: Step 1: Create a User Step 2: Create an Approval Process Step 3: Create a Custom Profile Step 4: Create a User Step 5: Test the Approval Process Summary Step 1: Create a User When you create a Force.

but you'll need to create a unique username for Bob. • • • In the Manager field.Tutorial #6: Creating an Approval Process • • • • In the Last Name field. select Basic User. In the Profile field. 1. Click Save. In the Alias field. enter your own email address. The Username field defaults to your email address. select Salesforce. 45 . Creating and using an approval process is just as easy as creating a workflow rule. You should now receive an email confirming the creation of the new user. In the Email field. See Also: Tutorial #6: Creating an Approval Process Step 2: Create an Approval Process Step 2: Create an Approval Process In this step you create an approval process that requires explicit approval from the manager if an invoice is over 2000. enter Large Invoice Value. In the User License field. enter Smith. enter bsmith. choose Invoice Statement. 3. so don't log in as Bob Smith yet or you'll have to immediately log back in as the administrator. 2. select the user you created when you signed up for your organization. 4. so that you will receive the approval requests routed to Bob Smith. Note: Write down Bob's username (his imaginary email address). Click Your Name ➤ Setup ➤ Create ➤ Workflow & Approvals ➤ Approval Processes. In the Manage Approval Processes For drop-down list. Click Create New Approval Process and choose Use Jump Start Wizard from the drop-down list. There's one more setup step to complete the approval process. in the form of an imaginary email address. 4. because you'll be logging in as him shortly. In the Name field.

c. Choose A specific value and select Open. Configure each field update action as shown. 8. Choose A specific value and select Closed. In the Value field enter 2000. Create new field update actions by clicking Add New and selecting Field Update for each related list in the following table. Select Automatically assign an approver using a standard or custom hierarchy field and choose Manager for the hierarchy field. 9. a. choose Invoice Value. This ensures that if a particular user starts the approval process. You've finished creating the approval process. You'll see a warning that you must activate the approval process. Enter the following values in the Specify Entry Criteria area. and when they're rejected. In the Field drop-down list. In the Operator drop-down list. Click View Approval Process Detail Page. 11. You'll create a user named Bob Smith in the next step. choose greater than. Set Initial Approval Status Status Set Final Approval Status Set Final Rejection Status Status Status 46 . Related List Initial Submission Actions Final Approval Actions Final Rejection Actions Name Field to Update Picklist Options Choose A specific value and select Pending. you have to define what happens to records when they're first submitted. 7. but before it can run. Click OK. when they're approved. Next to the Approval Assignment Email Template field. the user's manager is assigned as the approver. 10. 6. b. click the lookup icon and select the Large Invoice Template you just created.Tutorial #6: Creating an Approval Process 5. Click Save.

Scroll to the bottom of the profile edit page. 1. click Edit. See Also: Tutorial #6: Creating an Approval Process Step 1: Create a User Step 3: Create a Custom Profile Step 3: Create a Custom Profile A profile is a collection of permissions and other settings associated with a user or a group of users. The Initial Submission actions and Final Approval actions both lock the record. 13. if the record is rejected. it should be unlocked so changes can be made. 47 .” and “Delete”) are disabled for most profiles. You can change these permissions in custom profiles. Click Save.Tutorial #6: Creating an Approval Process 12. the permissions to access that object (“Read.. Create. 7. Default actions are associated with a few of the approval steps. but not standard profiles. 6. while the Final Rejection action unlocks it. Your organization has a number of standard profiles already defined. Click Activate to activate the approval process. 3. 14. This makes sense: if someone submits a record for approval.. select the Read. You'll create the new user in the next step. and under Custom Object Permissions. 4. enter Basic User. Click Save.” “Create. Then in your new custom profile. you'll create a custom profile that you can assign to users who need to access the custom objects in the Warehouse app.” “Edit. you'll enable object permissions so your users can access the objects. and Delete boxes for the Invoice Statements. In this step. 2. If you create a custom object. Select Clone next to Standard User. and Merchandise objects. On the detail page for your new profile. Verify that your screen looks like the following.. Tell Me More. and then click Save. Click Approval Processes to return to the approval list. Edit. Line Items. Likewise. In the Profile Name field. Click Your Name ➤ Setup ➤ Manage Users ➤ Profiles. This security setting ensures that access to custom objects and their data is only explicitly granted to users. it shouldn't be changed in the meantime. 5.

Tutorial #6: Creating an Approval Process

Tell Me More....
You've just seen how easy it is to create and edit a custom profile. If you need to edit many profiles, you can use enhanced profile list views to create a custom list view of your profiles and then edit the profiles from the list. For more information, see “Editing Profiles Using Profile Lists” in the Salesforce online help.

See Also:
Tutorial #6: Creating an Approval Process Step 2: Create an Approval Process Step 4: Create a User

Step 4: Create a User
When you create a Force.com application, it's automatically enabled to allow multiple users to log in. Now you can customize the application by configuring it to function differently depending on the profile of the user logging in. For example, you can grant read-only access to fields to a certain group of users, or make them completely invisible. You can also strictly enforce data sharing, so that a user sees only his or her records or those of his or her manager. In this step, you create a new user and link that user to your current user's account via the Manager field. You use this configuration to make sure that if the new user creates an invoice that meets certain conditions, the invoice is routed to his or her manager. 1. Click Your Name ➤ Setup ➤ Manage Users ➤ Users. 2. On the All Users page, click New User. 3. Enter the following information: • • • • • In the First Name field, enter Bob. In the Last Name field, enter Smith. In the Alias field, enter bsmith. In the Email field, enter your own email address, so that you will receive the approval requests routed to Bob Smith. The Username field defaults to your email address, but you'll need to create a unique username for Bob, in the form of an imaginary email address. Note: Write down Bob's username (his imaginary email address), because you'll be logging in as him shortly.

• • •

In the Manager field, select the user you created when you signed up for your organization. In the User License field, select Salesforce. In the Profile field, select Basic User.

48

Tutorial #6: Creating an Approval Process

4. Click Save. You should now receive an email confirming the creation of the new user. There's one more setup step to complete the approval process, so don't log in as Bob Smith yet or you'll have to immediately log back in as the administrator.

See Also:
Tutorial #6: Creating an Approval Process Step 3: Create a Custom Profile Step 5: Test the Approval Process

Step 5: Test the Approval Process
We can now put the approval process together and see it in action. If Bob Smith creates an invoice, and the total value of the invoice is greater than $2000, he will be able to click the new Submit for Approval button on the invoice statement. The app will send an email to his manager (using the email template you created earlier) and lock the record, preventing Bob from making any more changes. When the manager logs in, he or she can approve (or reject) the invoice. If the manager approves the invoice, you want its status updated to Closed. And if not, you want it to remain in the original Open status. In a real-world scenario, your business process might require you to email the invoice owner and ask for confirmation, and so on. Before testing the approval process, make sure that your Home page can display items that require approval. 1. 2. 3. 4. Click Your Name ➤ Setup ➤ Customize ➤ Home ➤ Home Page Layouts. Click Edit next to your home page layout. Select the Items to Approve option, if it is not already selected. Click Next, and then click Save.

While developing the application, you've been logged in as an administrator. To create a new record and test the approval process, you need to log out of your administrator account and log back in as a standard user. 1. Click Your Name ➤ Logout

49

Tutorial #6: Creating an Approval Process

2. Now log in as Bob Smith, the user you created earlier. If this is your first time logging in as Bob, you may have to change your password. 3. Select the Warehouse app. 4. Click the Invoice Statements tab. 5. Click New and create an invoice statement. 6. Add a New Line Item and enough units sold of the Wee Jet item that you created earlier to make the invoice value greater than $2000. 7. Click Save. 8. Click Submit for Approval. 9. Log out of the application. An email is sent to Bob Smith's designated manager who, for purposes of this tutorial, is you the administrator. Since you're the manager, you can check your email to verify this result. When you log in to the application as administrator, you see the pending approval request on the Home tab. (You may have to scroll down to see it.) The record is locked until the manager approves the invoice. An Approval field allows the manager to approve or reject the invoice and continue the workflow. Go ahead and Approve it.

Tell Me More....
From your Approval Process detail page, you can see a nice diagram of the approval process and the actions that will fire at each step. 1. In the familiar Your Name ➤ Setup area, click Approval Process and select the process you created. 2. Click View Diagram. The approval process diagram appears in a separate browser window.

50

See Also: Tutorial #6: Creating an Approval Process Step 5: Test the Approval Process 51 . This email alert was a fairly simple example. and the actions that need to be taken.Tutorial #6: Creating an Approval Process See Also: Tutorial #6: Creating an Approval Process Step 4: Create a User Summary Summary Approval processes help you enforce your business standards. but you can change the conditions for when an approval process runs.

Tutorial #7: Adding Programmatic Logic with Apex

Tutorial #7: Adding Programmatic Logic with Apex
Level: Advanced; Duration: 20-30 minutes

Apex is a strongly-typed, object-oriented, Java™-like programming language that runs on Force.com. Apex is used to add programmatic business logic to applications. For example you can use it to write triggers, Web services, and program controllers in your app's user interface layer. You've already added business logic using the declarative workflow environment. In this tutorial you'll create programmatic logic using Apex, which is ideal for juggling multiple records and complex logic. The business case you'll be working on requires that when a price for a piece of merchandise goes down, you will pass the savings along to your customers. To do this, you'll create an Apex trigger that updates all open invoices whenever the merchandise price decreases. A trigger is a set of code that fires at a particular time in the lifecycle of a record. In this case, you will create a trigger that fires after a merchandise record is updated. There are two ways to develop applications on Force.com: you can either use the online environment, as you've been doing up to this point, or use the Force.com IDE. If you don't have the IDE installed, it will take a moment to set up. However, if you are already familiar with the IDE, you know that it has syntax highlighting, code insight, and many other features that make development—especially team development—highly productive.

Prerequisites
Basic Knowledge For this tutorial, it helps to have basic knowledge of an object-oriented programming language like Java or C#, but it is not required. This tutorial can also be completed in the Force.com IDE, so familiarity with Eclipse is useful but not necessary. Software Requirements You can use the Force.com IDE for this tutorial if you want to. In that case you'll need the Force.com IDE plugin: wiki.developerforce.com/index.php/Force.com_IDE. If you need help creating a project, see Creating a Project in the Force.com IDE on page 88.

52

Tutorial #7: Adding Programmatic Logic with Apex

“Developer Mode,” “Modify All Data,” and “Author Apex” permissions Since this tutorial involves working with Apex, make sure that you have the proper permissions to create Apex classes.

See Also:
Step 1: Create an Apex Trigger Definition Step 2: Define a List Variable Step 3: Iterate Through the List and Modify Price Step 4: Test the Trigger Summary

Step 1: Create an Apex Trigger Definition
The first thing you need to do is create the trigger definition, which contains the trigger name, the affected object, and an action that fires the trigger. You can create triggers in the Web interface or in the Force.com IDE. Instructions are provided for both tools. To create a trigger in the Web interface: 1. 2. 3. 4. Click Your Name ➤ Setup ➤ Create ➤ Objects in the sidebar menu. Click your Merchandise custom object. On the Merchandise detail page, scroll down to Triggers and click New. Replace <name> and <events> so that the code matches the following:
trigger HandleProductPriceChange on Merchandise__c (after update) { }

5. If you're using the Web interface, click Quick Save, which will save your work and let you continue editing. Saving your work at this point also verifies that you've entered the code correctly, because if you've made syntax errors, the system won't let you save. To create the trigger in the Force.com IDE: 1. In the Package Explorer, right-click your project and click New ➤ Apex Trigger. 2. In the dialog box, enter HandleProductPriceChange for the name. 3. In the Object drop-down list, choose Merchandise__c. Note: If this object doesn't appear in the list of object, click Refresh Objects. (Ignore the warning that pops up about how you must select an operation.) 4. Select after update.

53

Tutorial #7: Adding Programmatic Logic with Apex

5. Click Finish and the file opens in the Editor.

Tell Me More....
Your trigger doesn't do anything yet, but it's now ready to accept any logic that you want to execute when a Merchandise record is updated. Before we get to the trigger logic, let's break up the trigger definition and examine each part. • • • •
HandleProductPriceChange—The name of the trigger. on Merchandise__c—The object the trigger acts on— in this case, your Merchandise__c custom object. (after update)—The action that fires the trigger. Apex triggers are fired in response to data actions, such as inserts,

updates and deletes—either before or after one of these events. The trigger you defined fires after a record is updated. { }—The code that goes between the curly brackets is called the body and determines what the trigger does. You'll code the trigger body next.

See Also:
Tutorial #7: Adding Programmatic Logic with Apex Step 2: Define a List Variable

Step 2: Define a List Variable
The first thing you need to do is define a list variable that will hold a list of line items. You don't need all the line items, so you'll select only those that are in the set of records that triggered this code to run and have their status set to Negotiating. 1. Between the curly braces of your trigger definition, enter the following comment and then declare a list variable.
// update invoice line items associated with open invoices List<Line_Item__c> openLineItems = [ ];

Note: For the sake of brevity, we won't comment everything here, but its good practice to comment your code.

2. Between the square brackets, enter a query that pulls information from your Line Item custom object.
List<Line_Item__c> openLineItems = [SELECT j.Unit_Price__c, j.Merchandise__r.Price__c FROM Line_Item__c j WHERE j.Invoice_Statement__r.Status__c = 'Negotiating' AND j.Merchandise__r.id IN :Trigger.new FOR UPDATE];

Note: We try to make our code samples fit on the page, so there are often line breaks where they aren't strictly needed. Apex ignores white spaces, so if the format of your code doesn't look exactly the same, that's OK. Also, Apex isn't case sensitive, so if you like to use lowercase, you can enter select instead of SELECT, for example.

54

Between the curly brackets. Declare a for loop. See Also: Tutorial #7: Adding Programmatic Logic with Apex Step 1: Create an Apex Trigger Definition Step 3: Iterate Through the List and Modify Price Step 3: Iterate Through the List and Modify Price In the previous step. Now you can iterate through the list using a for loop and modify an item's original price if its new price is lower. The lock remains until the trigger is complete. FROM—Determines which object or objects you want to access.Merchandise__r. for (Line_Item__c li: openLineItems) { if ( li.Merchandise__r. Let's take a look at that query in detail. for (Line_Item__c li: openLineItems) { if ( li. which is automatically initialized with the identifiers of the records being updated. The for loop is complete. which is written in the Salesforce Object Query Language (SOQL). What's contained in that list is determined by the query inside the square brackets. update openLineItems. The code uses a special variable. Between the for loop's curly braces.new. The openLineItems list holds a list of records from your Line_Item__c custom object.Price__c < li. The “j” in Line_Item__c j is an alias: it is a convenient shorthand that allows you to refer to Line_Item__c as “j”. preventing other program or users from making updates to them.. 1.Merchandise__r. add the following.Price__c. Before the trigger's final curly brace. Trigger. It pulls only the unique IDs of the records that are new.Unit_Price__c ){ } } 3..Unit_Price__c = li. Now you want to update the line items. In this case you want to return only those records where the status is Negotiating. enter a conditional if statement. • • • • • SELECT—Determines which fields are retrieved on the object. } } 4. enter code that updates the price. FOR UPDATE—This tells the platform to lock the records.Unit_Price__c ){ li.Price__c < li. for (Line_Item__c li: openLineItems) { } 2. WHERE—This is the start of the condition statement. AND—This is the second condition of your statement.. 55 .Tutorial #7: Adding Programmatic Logic with Apex Tell Me More. you created a list of line items and stored it in a variable called openLineItems.

Unit_Price__c. As you iterate.Unit_Price__c ) { }—Check to see if the price on the merchandise record is lower than the current price.Price__c.Merchandise__r.Invoice_Statement__r. update openLineItems. li.new FOR UPDATE]. Verify that your code looks like the following and then Save..id IN :Trigger.Merchandise__r. The final statement.Merchandise__r. you'll need to activate it.Merchandise__r.—Finally. } } update openLineItems. the current line item is assigned to the variable li.Unit_Price__c = li.. During development you typically leave a trigger inactive. That's simple enough. trigger HandleProductPriceChange on Merchandise__c (after update) { List<Line_Item__c> openLineItems = [SELECT j.Unit_Price__c = li. Then you'll 56 .Price__c < li. or modify an existing one.Merchandise__r. which becomes available after saving the trigger. • • If you're using the Web interface..Price__c FROM Line_Item__c j WHERE j.Merchandise__r. } Tell Me More.Unit_Price__c ){ li. update the unit price on the current line item (assigned to variable li) with the new merchandise price. for (Line_Item__c li: openLineItems) { if ( li. If you're using the IDE.Price__c < li. but what about that for loop? • • • for (Line_Item__c li: openLineItems) { }—Iterates over the list of open line item. updates the records in the database. if (li.Status__c = 'Negotiating' AND j. click the Metadata tab and change the status value to Active. select the Is Active checkbox. The only requirement is that you change the status field of the invoice statement to Negotiating. First you need to create a new invoice statement and order at least one product. j. 6. To try out the trigger.Tutorial #7: Adding Programmatic Logic with Apex 5. You only want to take an action if this is true.Price__c. See Also: Tutorial #7: Adding Programmatic Logic with Apex Step 2: Define a List Variable Step 4: Test the Trigger Step 4: Test the Trigger Now let's test the trigger in the app.

1. Tell Me More. you defined a trigger that executes whenever a merchandise record is saved with a lower unit price. and only then retrieve the related line item records. Note how the values of the line item and the invoice have automatically changed. that doesn't mean your trigger should update the record. 7. Now click on a Line Item. and neither of these cases requires the trigger to fire. You'll learn about testing in Tutorial #8: Adding Tests to Your Application on page 58. An important part of creating Apex triggers is making sure you have automated tests that verify that your trigger works as it should. For example.01. just because a merchandise record was updated. lowering the unit price. If you want an extreme reduction. You may have noticed that this trigger is a little wasteful: it initializes and operates on a list of all line item records that belong to invoice statements under negotiation. you built on the application by adding business logic that updates all open invoices when the unit price of a merchandise item goes down. 6. However. 8. Click the Merchandise tab. Triggers are very useful in scenarios such as these—when you need to update multiple records on a particular condition. change it to . You can have more than one trigger associated with an object that can be triggered under different events and conditions. Edit the record. 3. and select the Wee Jet record (or any other item used in the line items). See Also: Tutorial #7: Adding Programmatic Logic with Apex Step 3: Iterate Through the List and Modify Price Summary Summary In this tutorial.Tutorial #7: Adding Programmatic Logic with Apex lower the unit price of a merchandise item used in one of the line items of that invoice. 4. Take note of the Total Value of the invoice. or increased its price. Change its Status to Negotiating and click Save.. you may have updated the merchandise record's description. Ideally this trigger should iterate over the Trigger. Click the name of an existing invoice statement. 5. 2. Navigate back to the Invoice and the Line Item.. creating a new set of these records that pass the price criterion. and verify that your line item and invoice values are updated. See Also: Tutorial #7: Adding Programmatic Logic with Apex Step 4: Test the Trigger 57 .new set (the list of Merchandise records that have been updated). To do this. and note its Unit Price. Click the Invoice Statements tab..

which exercises the Apex trigger you just created. Duration: 20-30 minutes Testing is one of the most important steps in developing any application. which programmatically validate the code behavior and expected results. For example. Prerequisites Apex Tutorial You first need to create an Apex trigger as described in Tutorial #7: Adding Programmatic Logic with Apex on page 52. Software Requirements You can use the Force. If you need help creating a project. the platform requires that you test any Apex you write before that code can be deployed to a production environment. see Creating a Project in the Force.com/index. Testing ensures that your code behaves as it should and doesn't consume resources unnecessarily. To facilitate testing. To that end.com IDE on page 88.com IDE plugin: wiki. In that case you'll need the Force.developerforce.com_IDE. All Apex code has a set of limits that determine how many resources may be consumed. 58 . but also that it doesn't exceed these limits. Tests are also run before a new release of the platform is made available.Tutorial #8: Adding Tests to Your Application Tutorial #8: Adding Tests to Your Application Level: Advanced. Not only does testing benefit you (you will have more confidence in the applications you write).com IDE for this tutorial if you want to. to ensure that no backward compatibility problems are introduced. See Also: Step 1: Create an Apex Test Class Step 2: Add Test Methods to the Class Step 3: Write Code to Execute the Trigger Step 4: Execute the Test Step 5: View Code Coverage and Improve Tests Summary Step 1: Create an Apex Test Class All unit tests are contained in Apex classes. Good tests ensure that your code not only behaves as it should. but it also benefits the platform. Apex supports unit tests. there is a set limit on the number of queries that can be performed in a trigger.php/Force. In this tutorial you'll write and execute a unit test. In this step you create the class to contain the unit tests.

Then click New ➤ Apex Class. 3. 59 . The trigger that you created. enter the following code. See Also: Tutorial #8: Adding Tests to Your Application Step 2: Add Test Methods to the Class Step 2: Add Test Methods to the Class Now you can add a method to the class that will do the actual testing. and add these to the database... Click New. Invoice_Statement__c invoice = new Invoice_Statement__c(Status__c = 'Negotiating'). @isTest private class TestHandleProductPriceChange { } 4. only works when records are updated. enter the following code. replace the generated comment and code. which creates an invoice statement and inserts it into the database. The @isTest annotation tells Force. insert invoice. which you want to test. 2. Between the curly braces. Between the curly braces. choose Test Class. add the following code. right-click your project folder. In the Template field. Click Quick Save to save your work and continue editing. So the first thing you need to do is create test records in the database.Tutorial #8: Adding Tests to Your Application To create a new Apex class in the Web interface: 1. Start by creating the test method that will contain your three test procedures.com that all code within the Apex class is code that tests the rest of your code. enter TestHandleProductPriceChange for the name. In the IDE. Tell Me More. On the Create Apex Class page.. 2. You will now create test methods within this class that perform the actual tests. 2. 4. 1. In the editor pane. 3. static testMethod void testPriceChange() } { Note: If you're using the IDE. Click Finish to create the class.com IDE: 1. Click Your Name ➤ Setup ➤ Develop ➤ Apex Classes. You want the method to create an Invoice Statement as well as Merchandise and Line Item records. To create a new Apex class in the Force.

Line_Item__c[] lineItems = new Line_Item__c[] { new Line_Item__c(Invoice_Statement__c = invoice. Test. 4. add the following lines. Total_Inventory__c = 10). insert products. 60 . Description__c = 'test product 2'. Units_Sold__c = 6) }.price__c = 20. Unit_Price__c = 11. By marking where your actual test begins and ends. You have now set up the data. Merchandise__c[] products = new Merchandise__c[]{ new Merchandise__c(Name = 'item 1'. Testing also ensures that your code doesn't exceed certain governor limits—which limits the resources your Apex code may use. You'll do that in the next step. add the code to create new merchandise records.id. Price__c = 11. which is part of the testing framework that marks the point in your test code when your test actually begins. Merchandise__c = products[0]. products[0]. as that only happens when you update the price of a Merchandise record. new Line_Item__c(Invoice_Statement__c = invoice. the system won't count your setup code towards the governor limits.startTest(). Price__c = 10. ensuring that your test is a more accurate reflection of how it would behave in a production environment. After insert lineItems. Note: This code modifies the price of one of the Merchandise records.id. Description__c = 'test product 1'. raising its price. insert lineItems.. update products. Test.Tutorial #8: Adding Tests to Your Application 3. which is the condition you need for the trigger to fire. Note how the invoice statement that you created has a status set to Negotiating.stopTest().id. Unit_Price__c = 10. It then calls startTest(). Directly below insert invoice. You now need to write the code that will fulfill the other conditions for the trigger to fire: you need to lower the price of a piece of merchandise. new Merchandise__c(Name = 'item 2'. directly below insert products. The system will not consider the setup code and database operations that precede it to be part of the test. Total_Inventory__c = 10) }.id. Then. enter the code to add line items. 1. Merchandise__c = products[1]. Units_Sold__c = 3). See Also: Tutorial #8: Adding Tests to Your Application Step 1: Create an Apex Test Class Step 3: Write Code to Execute the Trigger Step 3: Write Code to Execute the Trigger The code in your test method doesn't really do much yet: it won't cause your trigger to execute.

because the price was raised in the setup code.assert(lineItems[0]. Note: These steps show how to execute steps in the Web interface. insert invoice.unit_price__c == 10). system.startTest(). it shouldn't have.com ➤ Run Tests. Description__c = 'test product 2'. Merchandise__c[] products = new Merchandise__c[]{ new Merchandise__c(Name = 'item 1'. and also check code coverage. Total_Inventory__c = 10) }.com IDE by right-clicking the class name in the Package Explorer and choosing Force. The remainder of this tutorial uses the Web interface. insert lineItems. Line_Item__c[] lineItems = new Line_Item__c[] { new Line_Item__c(Invoice_Statement__c = invoice.id. 3.id. Unit_Price__c = 11. update products. insert products. unit_price__c FROM Line_Item__c WHERE id IN :lineItems]. Unit_Price__c = 10. you need to check whether the price in the line items has changed.Tutorial #8: Adding Tests to Your Application 2. new Line_Item__c(Invoice_Statement__c = invoice.id.stopTest(). but you can also execute tests in the Force. You are now going to execute the tests. Price__c = 11. lineItems = [SELECT id. new Merchandise__c(Name = 'item 2'. Verify that your code looks like the following and then Save. unit_price__c FROM Line_Item__c WHERE id IN :lineItems]. but you should be able to follow along easily in the IDE. and look at the resulting code coverage. Units_Sold__c = 6) }. lineItems = [SELECT id. Units_Sold__c = 3). 61 .id. @isTest private class TestHandleProductPriceChange { static testMethod void testPriceChange() { Invoice_Statement__c invoice = new Invoice_Statement__c (Status__c = 'Negotiating'). } } See Also: Tutorial #8: Adding Tests to Your Application Step 2: Add Test Methods to the Class Step 4: Execute the Test Step 4: Execute the Test Force. Total_Inventory__c = 10). Price__c = 10.unit_price__c == 10).com has a testing framework that lets you execute tests.stopTest().assert(lineItems[0]. Ideally.price__c = 20. Test. Merchandise__c = products[1]. system. Test. products[0]. Now that you have updated the products. Add the following code after Test. Merchandise__c = products[0]. Description__c = 'test product 1'.

but we strive for perfection. and you have your code in the test class. the production code? If it 62 . that result would be flagged here. See Also: Tutorial #8: Adding Tests to Your Application Step 3: Write Code to Execute the Trigger Step 5: View Code Coverage and Improve Tests Step 5: View Code Coverage and Improve Tests You have written two sets of code. which we'll call production code. you can see that your Order_in_Stock validation rule has fired. Adding lots of asserts is a great way for you to test the expected behavior of your code. which we'll call test code. You have your trigger. • • Note also how the result page shows that you provided 80% coverage of the HandleProductPriceChange trigger. • It indicates whether your tests were successful or not. And you can see which records you created. By looking through the Debug Log. Click Run Test and you'll see output similar to the following. Navigate to your test class by clicking Your Name ➤ Setup ➤ Develop ➤ Apex Classes. or only some portion of. 2. It indicates code coverage: how many lines of code you executed in some other class or trigger. and then click your test class. This result tells you a number of important things. you'll view the code coverage to see where you need to add more test cases to bring it up to 100%. for example. The term code coverage refers to how much of your production code is covered by testing code. how many queries you executed. TestHandleProductsPriceChange. In other words: when someone runs your testing code. If the boolean condition in the system. That's enough code coverage to deploy. does it execute all.Tutorial #8: Adding Tests to Your Application 1.assert statement that you added to the test had failed. and more. It provides detail about the execution of the test. In the next step.

// lower price Test. Synchronizing is easy (right-click your class and choose Force. click 80.assert(lineItems[0]. Note: If you have been using the Force. // changed!! 6. 5. keep using it. 2. That red line is good indicator that your test isn't complete.unit_price__c == 10). Click Save. Developing in both the IDE and the Web interface at the same time requires that you synchronize with the server every time you switch back and forth. Starting with products[0]. replace the code up to the next curly brace with the following. 3.com ➤ Synchronize with Server). line 13 wasn't executed because we don't lower the price of a merchandise item. // unchanged System. // raise price products[1]. In the Code Coverage section. So let's modify your test method to improve your code coverage.com IDE for this tutorial. The red highlight marks lines that have not been executed. 63 .price__c = 20. lineItems = [SELECT id.startTest(). that could mean your production code contain bugs in the untested code. Close the Code Coverage window and then click Your Name ➤ Setup ➤ Develop ➤ Apex Classes and select your test class TestHandleProductPriceChange.price__c = 5.Tutorial #8: Adding Tests to Your Application only executes a portion of the code. products[0]. Click Edit. You can make these concepts a little more concrete by looking at a graphical code coverage chart. and you'll see that you have 100% code coverage. The blue highlight marks lines of code that have been covered (executed) as a result of our test method. Now click Run Test again. Test. unit_price__c FROM Line_Item__c WHERE id IN :lineItems].stopTest(). In this case. The Code Coverage page opens. System.unit_price__c == 5). 7. update products. we only raise it. 4.assert(lineItems[1]. but it's even easier to avoid! 1.

then raising or lowering the price shouldn't have any effect. and the test case you have just written misses one. But it's important to note that code coverage isn't the only goal for testing.Tutorial #8: Adding Tests to Your Application See Also: Tutorial #8: Adding Tests to Your Application Step 4: Execute the Test Summary Summary In this tutorial you created tests for the Apex trigger and saw how the integrated testing tools can help you attain 100% code coverage. Right now it only checks invoice statements that have a status of Negotiating. See Also: Tutorial #8: Adding Tests to Your Application Step 5: View Code Coverage and Improve Tests 64 . ideally you should also check all possible scenarios. It should also check other status values. For example. if an invoice statement does not have a status of Negotiating. Creating unit tests as you develop is necessary for deployment and it's also the key to successful long-term development.

1. it helps to have basic knowledge of markup languages like HTML and XML. and is highly flexible.Tutorial #9: Building a Custom User Interface Using Visualforce Tutorial #9: Building a Custom User Interface Using Visualforce Level: Intermediate. It allows you to see code and preview the page at the same time. in case they are different. as well as update the counts on each. The purpose of the count sheet is to update the computer system with a physical count of the merchandise. and an Apex-based controller model.com platform. In this tutorial. See Also: Step 1: Enable Visualforce Development Mode Step 2: Create a Visualforce Page Step 3: Add a Stylesheet Static Resource Step 4: Add a Controller to the Page Step 5: Display the Inventory Count Sheet as a Visualforce Page Step 6: Add Inline Editing Support Summary Step 1: Enable Visualforce Development Mode Development Mode embeds a Visualforce page editor in your browser. a library of reusable components that can be extended. Prerequisites Basic Knowledge For this tutorial. Visualforce gives you a lot more control over the user interface by providing a view framework that includes a tag-based markup language similar to HTML. but it is not required. 65 . 3. 2. Duration: 30–45 minutes Visualforce is a component-based user interface framework for the Force. Click Your Name ➤ Setup ➤ My Personal Information ➤ Personal Information. Development Mode also adds an Apex editor for editing controllers and extensions. Click Edit. Visualforce supports the Model-View-Controller (MVC) style of user interface design. you will use Visualforce to create a new interface for the Warehouse application that displays an inventory count sheet that lets you list all Merchandise inventory. Select the Development Mode checkbox and click Save. In previous tutorials you built and extended your application by using a user interface that is automatically generated.

salesforce. Click the Page Editor link in the bottom left corner of the page. if your Salesforce instance is https://na1. Click the Create Page CountSheet link to create the new page. 66 . It should look like this.com.com/apex/CountSheet. The Page Editor tab displays the code and a preview of the new page (which has some default text). 1. 3.salesforce. You will get an error message: Page CountSheet does not exist. For example. the new URL would be https://na1. 2. In your browser. add the text /apex/CountSheet to the URL for your Salesforce instance.Tutorial #9: Building a Custom User Interface Using Visualforce See Also: Tutorial #9: Building a Custom User Interface Using Visualforce Step 2: Create a Visualforce Page Step 2: Create a Visualforce Page In this step you create a Visualforce page that will serve as an inventory count sheet.

com/workbook/styles. In order for your pages to reference a stylesheet. Notice that the code for the page looks a lot like standard HTML. and arrangement of text on your page. click Your Name ➤ Setup ➤ Develop ➤ Static Resources and click New. so we've created one for you.. In your browser.zip file you downloaded.force. That's because a Visualforce page combines HTML tags.. The page reloads to reflect your changes. go to developer. 67 . Tell Me More. The code for the page should now look like this. and go ahead and remove the comments. so change the contents of the <h1> tag to Inventory Count Sheet.. with Visualforce-specific tags. 4. Download the file and save it to your desktop.Tutorial #9: Building a Custom User Interface Using Visualforce 4. for this purpose. so you're going to use a custom stylesheet (CSS file) to specify the color. 3.com. it can be referenced by any of your Visualforce pages. which start with <apex:> See Also: Tutorial #9: Building a Custom User Interface Using Visualforce Step 1: Enable Visualforce Development Mode Step 3: Add a Stylesheet Static Resource Step 3: Add a Stylesheet Static Resource You want your Warehouse application to look slick. such as <h1>. font. Click the Save icon at the top of the Page Editor. a standard Web technology. In the Name field. Back in the app. To add a style sheet as a static resource: 1. In the Cache Control picklist choose Public. Most Web pages and Web designers use CSS. Click Browse and find the styles. A static resource is a file or collection of files that is stored on Force. you have to upload it as a static resource. <apex:page> <h1>Inventory Count Sheet</h1> </apex:page> 5. You don't really want the heading of the page to say “Congratulations”. 2. Once your stylesheet is added as a static resource. enter styles. 5.

Click Save. which gives you a drop-down list of the elements that are available in this context. the header.css')}" /> 6. and the sidebar. so add a new line below the first <apex:page> tag and type <apex: 4. select it. Modify the attributes of the <apex:page> tag and enter the following code to remove the standard stylesheet. 1. 2. then Force. Start typing stylesheet and when you see apex:stylesheet. 68 .styles. Click the Save icon at the top of the Page Editor. Just as you did when you created the page.styles. add the text /apex/CountSheet to the URL for your Salesforce instance. Now you need to tell the page where to find the stylesheet.com uses a global content delivery network of cache servers to hold copies of your static files.Tutorial #9: Building a Custom User Interface Using Visualforce 6. Now you need to modify your Visualforce page to reference the stylesheet. <apex:page standardStylesheets="false" showHeader="false" sidebar="false"> 3. 'styles. <apex:stylesheet value="{!URLFOR($Resource. Note: If your Visualforce pages are exposed on a public website. 5. Now specify the location of the stylesheet as shown. Verify that your code looks like the following: <apex:page standardStylesheets="false" showHeader="false" sidebar="false"> <apex:stylesheet value="{!URLFOR($Resource.css')}" /> <h1>Inventory Count Sheet</h1> </apex:page> 7. The editor has code insight. 'styles.

Tutorial #9: Building a Custom User Interface Using Visualforce Note how the page now looks very different. because you've indicated that the page should use a controller. so you can enter the text on a new line. the controller may contain the logic that should be executed when a button is clicked. Tell Me More. If the Page Editor isn't open on your Visualforce page. You won't notice any change on the page. 2. Next. A controller also typically interacts with the model (the database)—exposing data that the view might want to display. All Force. add the standard list controller definition.styles. the view (the Visualforce page) interacts with a controller. However. or create custom controllers from scratch. In MVC. and a file within that resource. 69 . 1. it's because you've already encountered it to dynamically evaluate values when the Visualforce page is rendered. the variable will be available to you in the body of the page and it will represent a list of Merchandise records. In this tutorial you'll use the default controller. Let's take a look at that stylesheet code in a little more detail. The editor ignores whitespace.. and defined the variable products. You can extend the standard controllers to add new functionality. <apex:page standardStylesheets="false" showHeader="false" sidebar="false" standardController="Merchandise__c" recordSetVar="products"> 4. click Page Editor to edit the page.. which exposes some functionality to the page. Modify your code to enable the Merchandise__c standard controller by editing the first <apex:page> tag. See Also: Tutorial #9: Building a Custom User Interface Using Visualforce Step 2: Create a Visualforce Page Step 4: Add a Controller to the Page Step 4: Add a Controller to the Page Visualforce's Model-View-Controller design pattern makes it easy to separate the view and its styling from the underlying database and logic. • • $Resources is a global variable which Visualforce has access to. so in many cases you don't need to write the code for the controller yourself. and calculates the URL that should be generated in your final page. the controller is usually an Apex class. For example. Click the Save icon at the top of the Page Editor. In our case.com objects have default standard controllers that can be used to interact with the data associated with the object. and the standard header and sidebar are no longer present. <apex:page standardStylesheets="false" showHeader="false" sidebar="false" standardController="Merchandise__c"> 3. If the syntax looks familiar. you refer to the resource called "styles" which you created earlier. With $Resource. the title is in a different font and location.. The URLFOR() function locates the static resource.

See Also: Tutorial #9: Building a Custom User Interface Using Visualforce Step 3: Add a Stylesheet Static Resource Step 5: Display the Inventory Count Sheet as a Visualforce Page Step 5: Display the Inventory Count Sheet as a Visualforce Page You now have all the functionality in place to flesh out the Visualforce page. 70 . <apex:dataTable value="{!products}" var="pitem" rowClasses="odd. which provides additional controller support for listing a number of records with pagination.name}"/> </apex:column> </apex:dataTable> 6. enter the following. It will display a table of all the merchandise records. The headerValue attribute has simply provided a header title for the column. will ensure that a new variable. and you will see your table appear. for one single iteration. start typing <apex:f on a new line. and determine where it gets its data by looking up the appropriate field in the pitem variable. 3. The form will allow you to make updates to the page. Click Save. On one or more lines within the tag. <apex:dataTable value="{!products}" var="pitem" rowClasses="odd. The recordSetVar attribute enables a standard list controller. Now you are going to define each column.even"> 5. and below it you'll see a list of rows: one for each merchandise record. In the line below the </h1> tag. Now you need to add some attributes to the dataTable tag. Press Enter and notice that the system generates the opening and closing tags for you. 1.The value attribute indicates which list of items the dataTable component should iterate over. Place your cursor between the tags and create a data table. Start by typing <apex:d and press Enter to select dataTable from the drop-down list. products. The expression {!pitem.. which you've set to products. 4. 2. Add the following code between the opening and closing dataTable tags..name} indicates that we want to display the name field of the current row. and highlight <apex:form> when it appears in the drop-down list. to the pitem variable. will contain the set of records to be displayed on the Visualforce page.Tutorial #9: Building a Custom User Interface Using Visualforce Tell Me More.. The rowClasses attribute assigns CSS styling names to alternate rows. The var attribute assigns each item of that list. Its value.even"> <apex:column headerValue="Product"> <apex:outputText value="{!pitem. together with an input field on each so that you can update the inventory count.

and invokes a method called quicksave on the standard controller. 9. You can safely remove this–it will just make things look less pretty! Every standard controller has various methods that exist for all Force. The inputField will display a value. It's this list that the dataTable component uses. • The dataTable component produces a table with rows. and the recordSetVar to products. and each row is found by iterating over a list. add two more columns. the controller automatically populated the products list variable with merchandise records retrieved from the database.Total_Inventory__c}"/> </apex:column> Note: The second column is an inputField. enter the following code directly above the </apex:form> line.Tutorial #9: Building a Custom User Interface Using Visualforce 7. The rowClasses and styleClass attributes simply use some of the styles from the CSS style sheet that you loaded in the static resource. That statement var="pitem" assigns a variable called pitem that holds the current row. and provides an input field for the physical count. add a button that will modify the physical count on any row and refresh the values on the page. As a result. <apex:column headerValue="Inventory"> <apex:outputField value="{!pitem. Now. • • • 71 . which updates the product with the new count. after the closing tag for the first column.. Click Save and you have an inventory count sheet! It lists all the merchandise records.. 8.Total_Inventory__c}"/> </apex:column> <apex:column headerValue="Physical Count"> <apex:inputField value="{!pitem. which updates the values on the records. you're updating the physical count of the product and performing a quick save.. As a final embellishment. but it will also allow you to change it. The commandButton component displays the button. You need a way to reference the current row as you iterate over the list.com objects. <br/> <apex:commandButton action="{!quicksave}" value="Update Counts" /> Tell Me More. The standard controller you used for this page was set to Merchandise__c. not an outputField. To do this. Here. displays the current inventory.

If you have enough records to page through them. <apex:inlineEditSupport event="ondblclick" showOnEdit="update"/> 4. as follows. modify the update button to give it an ID and a style class name. Replace the commandButton with the following. The style class name is used in styles. you will be able to edit the inventory count by double-clicking a field in the Inventory column. In this step. Instead of using an inputField to edit the physical count in the last column in the previous step.Tutorial #9: Building a Custom User Interface Using Visualforce • Although pagination isn't shown in this example. insert the inlineEditSupport component. <apex:column headerValue="Physical Count"> <apex:inputField value="{!pitem. 1. Now that you've added the inlineEditSupport component. Within the inventory column.Total_Inventory__c}"> </apex:outputField> 3. since inline editing makes the physical count input field unnecessary. <apex:outputField value="{!pitem. The following procedure shows how to do this. the functionality is there. <apex:commandLink action="{!next}" value="Next" rendered="{!hasNext}" /> See Also: Tutorial #9: Building a Custom User Interface Using Visualforce Step 4: Add a Controller to the Page Step 6: Add Inline Editing Support Step 6: Add Inline Editing Support You now have a Visualforce page that contains a table that displays all the merchandise records and allows you to edit the inventory count through the physical count input field. Delete the following markup for the physical count column. which contains this field.css to hide the update button the first time the page renders. break up the outputField component so that it has an end tag. After carrying out this step. add the following code below the commandButton for page-flipping action. Between the outputField's start and end tag. <apex:commandButton id="update" action="{!quicksave}" value="Update Counts" styleclass="updateButton"/> 72 . Also. you can make the inventory column editable by adding an inlineEditSupport component as a child component of the outputField component. The ID is referenced by the inlineEditSupport component to show the button during editing.Total_Inventory__c}"/> </apex:column> 2. you remove the last column. you modify this table to add inline editing support for the inventory output field.

name}"/> </apex:column> <apex:column headerValue="Inventory"> <apex:outputField value="{!pitem.even"> <apex:column headerValue="Product"> <apex:outputText value="{!pitem. 'styles.css')}"/> <h1>Inventory Count Sheet</h1> <apex:form> <apex:dataTable value="{!products}" var="pitem" rowClasses="odd. • See Also: Tutorial #9: Building a Custom User Interface Using Visualforce Step 5: Display the Inventory Count Sheet as a Visualforce Page Summary 73 . which is a DOM event and means that the output field will be made editable when you double-click it. <apex:page standardStylesheets="false" showHeader="false" sidebar="false" standardController="Merchandise__c" recordsetVar="products"> <apex:stylesheet value="{!URLFOR($Resource. The styleclass attribute on commandButton links this button to an entry in styles. Double-click any cell in the inventory column. 8.. Notice that the Update Counts button is hidden initially. The Update Counts button is hidden through its style specification in the static resource file styles. Notice how the field dynamically becomes an input field and the Update Counts button appears.. This attribute is set to the ID of the Update Counts button.Total_Inventory__c}"> <apex:inlineEditSupport event="ondblclick" showOnEdit="update"/> </apex:outputField> </apex:column> </apex:dataTable> <br/> <apex:commandButton id="update" action="{!quicksave}" value="Update Counts" styleclass="updateButton"/> </apex:form> </apex:page> 6. Modify the count value and click Update Counts to commit this update.Tutorial #9: Building a Custom User Interface Using Visualforce 5. The page now displays the inventory count table with two columns. Click Save. the showOnEdit attribute causes the Update Counts button to appear on the page during an inline edit.css. Also. Your Visualforce markup should look like the following. an undo button dynamically appears to the right of the field which allows you to cancel out of this edit operation.styles. Also. Tell Me More.css. 7.. • The event attribute of the inlineEditSupport component is set to "ondblclick".

Now that you have created some Visualforce components. For example. It also provides a way of saving records. the controller automatically queries the database and finds all merchandise records and assigns them to the products variable. Your page is highly configurable. For example. The page also makes use of a lot of functionality provided by the standard controller behind the scenes. You'll find out about that in the Tutorial #10: Creating a Public Web Page Using Sites tutorial. See Also: Tutorial #9: Building a Custom User Interface Using Visualforce Step 6: Add Inline Editing Support 74 . you can easily modify which data is displayed in each row by modifying the column components. you can expose this functionality on a public website. through its quicksave method.Tutorial #9: Building a Custom User Interface Using Visualforce Summary Congratulations! You have created a new interface for your Warehouse application by creating a Visualforce page that uses a standard controller.

See Also: Step 1: Create a Product Catalog Page Step 2: Register a Force. Select the CountSheet page you created earlier. sometimes you need to eliminate the login—for example on a public website. register your Force. and expose the Visualforce page you created as a public product catalog on the Web. And because sites are built on native pages.com Domain Name Step 3: Create a Force. If you're still in the Visualforce editor. You can also make the site's pages match the look and feel of your company's brand.com domain name.com supports your application in a multi-user environment. You can publicly expose any information stored in your organization through a branded URL of your choice. The new Product Catalog page will show description and price instead of inventory and count. Because sites are hosted on Force.com Site Step 4: Configure and Test the Site Summary Step 1: Create a Product Catalog Page In this step. While Force. enable Sites for your organization. as described in Tutorial #9: Building a Custom User Interface Using Visualforce on page 65. 3.Tutorial #10: Creating a Public Web Page Using Sites Tutorial #10: Creating a Public Web Page Using Sites Level: Intermediate. In this tutorial. there are no data integration issues. Duration: 20-30 minutes The application you just created requires that you log in use it. 75 . 1. You can also enable users to register for.com servers. you clone the inventory count page you created earlier. 2. Click Your Name ➤ Setup ➤ Develop ➤ Pages. you will create a Visualforce page. Sites enables you to create public websites and applications that are directly integrated with your organization—without requiring users to log in with a username and password. an associated portal seamlessly from your public site. data validation on collected information is performed automatically. you click Back in your browser until you see the Setup area. Prerequisites Visualforce Tutorial You first need to create the Visualforce page. Click Clone. or log into.

Description__c}"/> </apex:column> 8. 10. Change Inventory to Description and change Total_Inventory__c to Description__c. 6.css')}"/> <h1>Merchandise Catalog</h1> <apex:dataTable value="{!products}" var="pitem" rowClasses="odd. <apex:column headerValue="Inventory"> <apex:outputField value="{!pitem. remove the opening and closing <apex:form> and <apex:commandButton> tags. it's easy to clone a Visualforce page.even"> <apex:column headerValue="Product"> <apex:outputText value="{!pitem. 5. The standard controllers for the Visualforce page make all your data readily accessible. as shown. 76 . change the contents of the <h1> tag to Merchandise Catalog. but changing the table heading and the data within.. Now you'll make a similar change on the next column to display the price.Price__c}"/> </apex:column> 9.Total_Inventory__c}"/> </apex:column> 7.. Then change Total_Inventory__c to Price __c.Price__c}"/> </apex:column> </apex:dataTable> </apex:page> Tell Me More. On the Page Editor tab.Tutorial #10: Creating a Public Web Page Using Sites 4.Description__c}"/> </apex:column> <apex:column headerValue="Price"> <apex:outputField value="{!pitem.name}"/> </apex:column> <apex:column headerValue="Description"> <apex:outputField value="{!pitem. find the following lines. • • Lots of components on the Force. <apex:column headerValue="Description"> <apex:outputField value="{!pitem. <apex:column headerValue="Price"> <apex:outputField value="{!pitem. In the Page Editor. The code should look like the following. Change Physical Count to Price. change the Label and Name fields to Catalog. you can display data from different fields.. because you don't want to accept input on this page. Then change inputfield to outputfield. and as you just saw.com platform can be cloned. In the editor. Finally. Verify that your code looks like the following and then click Save.styles. There are a few important things to note here. <apex:page standardStylesheets="false" showHeader="false" sidebar="false" standardController="Merchandise__c" recordSetVar="products" > <apex:stylesheet value="{!URLFOR($Resource. By simply changing a couple of values in a table. You're keeping the same table. 'styles.

such as mycompany.com domain name after you have registered it. 3. and not contain two consecutive underscores. not include spaces.com. To get started. which hosts your site. the changes related to site creation are tracked in your organization's Setup Audit Trail and the Site History related list. if you choose “mycompany” as your domain prefix.com domain by doing the following. It may take up to 48 hours for your registration to take effect. 1. Caution: You cannot modify your Force.mycompany. Salesforce.com Site 77 . See Also: Tutorial #10: Creating a Public Web Page Using Sites Step 1: Create a Product Catalog Page Step 3: Create a Force. plus force. 2. For example. If it is not unique. It must begin with a letter. your domain name would be http://www. Enter a unique name for your Force.com domain. After you accept the Terms of Use and register your Force. but you can also extend the controller to create custom functionality.com. 4.com domain. Click Your Name ➤ Setup ➤ Develop ➤ Sites.force. register your company's Force.com Domain.com Domain Name Your unique Force. and must be unique in your organization. Congratulations! You are now ready to create your first Force. is constructed from the unique domain prefix that you register.com site. See Also: Tutorial #10: Creating a Public Web Page Using Sites Step 2: Register a Force.com Domain Name Step 2: Register a Force. you are prompted to change it.com recommends using your company's name or a variation. Read and accept the Sites Terms of Use by selecting the checkbox. and even create your own controller from scratch. not end with an underscore. Click Check Availability to confirm that the domain name you entered is unique. This name can contain only underscores and alphanumeric characters.com domain. Click Register My Force.Tutorial #10: Creating a Public Web Page Using Sites • Did you notice how easy it was to change an input field to an output field? The Visualforce standard controller is powerful indeed. 5.

fill in the site details: a. In the Site Label and Site Name fields enter Catalog. The platform has a number of conservative controls in place for data security. b. Select the Active checkbox. In the Active Site Home Page field enter Catalog. In this step you will toggle this security setting for the Merchandise object. 78 . Click Save. and established a default page. Go to the Sites list by clicking Your Name ➤ Setup ➤ Develop ➤ Sites. 4.com Domain Name Step 4: Configure and Test the Site Step 4: Configure and Test the Site Now that you've created your site. Go to the Sites page by clicking Your Name ➤ Setup ➤ Develop ➤ Sites. and then visit your new site. Click New.com Site Now that you have registered your domain. 1. See Also: Tutorial #10: Creating a Public Web Page Using Sites Step 2: Register a Force. unless you explicitly enable it. One of the controls ensures that data isn't displayed. even on public pages. c. 2. you can make the Merchandise Catalog Visualforce page you created the home page for your new site. On the Site Edit page. you're almost ready to try it out.Tutorial #10: Creating a Public Web Page Using Sites Step 3: Create a Force. 1. The Site Edit page appears. 3.

it should be called Catalog. and made it the home page for that site. Go back to the setup page. 7.Tutorial #10: Creating a Public Web Page Using Sites 2. Scroll down to the Custom Object Permissions section and select the Read permission for the Merchandise object. Now go back to your website and refresh your browser and you should see your page. Let's fix this. Force. instead of seeing your Merchandise Catalog page. click Edit..com/Meme (depending on your domain name of course). 6. • You've assigned a single Visualforce page to the site. However. Click Save..force.com keeps track of the number of page views a Developer Edition site and imposes a daily bandwidth limit on the site. You can go ahead and create additional Visualforce pages and assign them to the site as well. you probably didn't set your Active Site Home Page to Catalog in the previous step. This is because the anonymous website viewer hasn't yet been granted permission to view the data that the page is displaying. This action opens either a new tab or a new window (depending on your browser). Click the Site URL link for the Product Catalog site. Click the Site Label link. Note: If you still have an authorization required message. you'll see a large Authorization Required page. if you add a page Meme to the site. For example. 3.na1. 5. Tell Me More. Click Public Access Settings and then in the Profile Detail section. • 79 . you will be able to access it with a URL something like http://workbook-developer-edition.. 4.

Then you registered a unique Force. all without having to log in. You'll do that next in the tutorial Tutorial #11: Creating a Store Front on page 81.Tutorial #10: Creating a Public Web Page Using Sites • Sites sites lets you make use of a global content delivery network for fast access and caching of your site pages on production environments. registered the page as your home page. Now that you have a site with a product catalog. You simply need to modify the page component to include a cache instruction. See Also: Tutorial #10: Creating a Public Web Page Using Sites Step 4: Configure and Test the Site 80 .com Site Summary Summary Congratulations. tweaked the security. the next logical step is to provide a way for people to order merchandise. and tested the site to see that it works. <apex:page cache="true" expires="600"> See Also: Tutorial #10: Creating a Public Web Page Using Sites Step 3: Create a Force. you cloned a Visualforce page and then enabled your Developer Edition organization for Sites functionality. you have created a public website! Anyone in the world can access the site you just created and look at your home page.com domain name. To create the site.

Tutorial #11: Creating a Store Front Tutorial #11: Creating a Store Front Level: Intermediate. which returns the products your store front will display. If you need help creating a project. and contain code that will be executed in response to page actions. Duration: 30 minutes Apex is an object-oriented programming language. discover more Apex syntax. In this tutorial you are going to create a simple Visualforce store front page. as you did in the previous tutorial. In that case you'll need the Force. you'll create an Apex class.” “Modify All Data.com IDE plugin: wiki. Along the way. and shop(). you're now going to write the controller code yourself. and learn how to pass values between a Visualforce page and its controller.” and “Author Apex” permissions Since this tutorial involves working with Apex. Using Apex. and much more. create Web services.com IDE on page 88. which will use a controller you write in Apex. see Creating a Project in the Force. make sure that you have the proper permissions to create Apex classes. make calls to the database. 81 . Prerequisites Warehouse App You first need to create the basic Warehouse application and add relationships.com_IDE. which executes when products have been selected. such as a command button being clicked.com IDE for this tutorial if you want to. send email.developerforce. Controllers typically retrieve the data to be displayed in a Visualforce page. Your rudimentary store front will have two methods: getProducts(). “Developer Mode.php/Force. See Also: Step 1: Create a Controller Step 2: Add Methods to the Controller Step 3: Create the Store Front Step 4: Bonus Step—Updating the Page with AJAX Summary Step 1: Create a Controller Instead of using the default controller.com/index. as described in Tutorial #2: Adding Relationships on page 14. you can create classes and methods. Software Requirements You can use the Force.

1. Now you'll add methods to it. } public Decimal count { get. right-click your project folder and select New ➤ Apex Class. You'll start by adding the shop() method. Add the following code as the definition of the class and then click Quick Save. public DisplayMerchandise[] getProducts() { if (products == null) { 82 . set. set. together with a count. On the Create Apex Class page. Click New. It has no methods or fields.Tutorial #11: Creating a Store Front To create the class in the Web interface: 1. } 2. Add the following code to the class (just after the public class StoreFront { line). You also want the shop to display merchandise items. You now have a rudimentary class for your controller. See Also: Tutorial #11: Creating a Store Front Step 2: Add Methods to the Controller Step 2: Add Methods to the Controller In the last step you created a custom controller. public class DisplayMerchandise { public Merchandise__c merchandise { get. public PageReference shop() { return null. In the IDE. and a new inner class called DisplayMerchandise to hold the data. so that the end user can select how many of each item they wish to purchase. which is going to initialize the products. public class StoreFront { } To create the class in the Force. 3. It's not going to do anything yet. specify StoreFront for the name. Click Finish. so you'll add those in the next step. Within the current class (on the next line). Click Your Name ➤ Setup ➤ Develop ➤ Apex Classes.merchandise = item. 2. but you'll need it as a placeholder for the action that occurs when someone clicks the Shop button. DisplayMerchandise[] products. 2. } } 3. define the method getProducts(). define a field to hold a list of DisplayMerchandise.com IDE: 1. 3. On the next line. } public DisplayMerchandise(Merchandise__c item) { this.

It uses standard Apex classes and methods to access the database. which is then returned. public class StoreFront { public PageReference shop() { return null. name. set.. } public DisplayMerchandise(Merchandise__c item) { this. } public Decimal count { get. price__c FROM Merchandise__c WHERE Total_Inventory__c > 0]) { products.Tutorial #11: Creating a Store Front products = new DisplayMerchandise[]{}. Tell Me More. for (Merchandise__c item : [SELECT id. also called a SOQL query) returning all Merchandise records that have a positive total inventory. The constructor lets you create a new DisplayMerchandise instance by passing in an existing Merchandise record. set. See Also: Tutorial #11: Creating a Store Front Step 1: Create a Controller Step 3: Create the Store Front 83 . The DisplayMerchandise class “wraps” the Merchandise type that you already have in the database. adding them to a list of DisplayMerchandise products. description__c.merchandise = item. Verify that your code looks like the following and then click Save. for (Merchandise__c item : [SELECT id. price__c FROM Merchandise__c WHERE Total_Inventory__c > 0]) { products. The instance variable products is defined as a list of DisplayMerchandise instances. adding a new decimal field. } } return products. } } public DisplayMerchandise[] getProducts() { if (products == null) { products = new DisplayMerchandise[]{}. public class DisplayMerchandise { public Merchandise__c merchandise { get. description__c..add(new DisplayMerchandise(item)). It then iterates over the records returned by the query. } DisplayMerchandise[] products.. The getProducts() method executes a query (the text within square brackets. name. } } return products. } 4. } } You have now finished defining a simple controller.add(new DisplayMerchandise(item)).

1.salesforcecom/apex/StoreFront.name}"/> </apex:column> <apex:column headerValue="Price"> <apex:outputText value="{!pitem. You are now ready to insert the contents of the form between the opening and closing form tags. You'll see the familiar error message. You will create a table that iterates over the products.count}"/> </apex:column> </apex:dataTable> <br /> <apex:commandButton action="{!shop}" value="Buy" /> 6. <apex:page standardStylesheets="false" showHeader="false" sidebar="false" controller="StoreFront" > <apex:stylesheet value="{!URLFOR($Resource. Click the Page Editor tab at the bottom. 'styles. add /apex/StoreFront to the end of your instance. For example: https://na1. 2.Tutorial #11: Creating a Store Front Step 3: Create the Store Front Your store front uses another Visualforce page for the store front.styles. Replace the text in the editor with the following.merchandise. In the address bar of your browser. and a button to call the shop method.merchandise. 5. between the open and close form tags. 4. 84 . Your Store Front page should look like this. <apex:dataTable value="{!products}" var="pitem" rowClasses="odd. 3. Enter this code on the next line. so let's create that now. Click the Create Page StoreFront link.price__c}"/> </apex:column> <apex:column headerValue="#Items"> <apex:inputText value="{!pitem.even"> <apex:column headerValue="Product"> <apex:outputText value="{!pitem.css')}"/> <h1>Store Front</h1> <apex:form> </apex:form> </apex:page> Note: The controller="StoreFront" attribute ensures that the Visualforce page you are creating will use the StoreFront Apex class as its controller. Click Save.

.. and is assigned to the pitem variable in the Visualforce page as the dataTable iterates. It shows you how Visualforce transparently passes data back to your controller. the shop() method that you wrote in the controller has access to the merchandise counts that were entered by the end-user on the Visualforce page. 85 . Let's take a look. • The value attribute of the dataTable is set to "products". For example. you will simply display that data in the page again (using a nifty AJAX page update). In a real-world scenario you could imagine emailing the order. a method with the exact same name is used in the Apex controller. The Visualforce page has an action. This step shows you how to access that data in the controller. Each of these will form a new row. The getProducts() method in your controller returns an array of DisplayMerchandise objects. for example https://na1. adding the items to a shopping basket. where it can be processed. Visualforce automatically looks for a method called getProducts() in your Apex controller. 2. 1.Tutorial #11: Creating a Store Front Tell Me More.salesforce.. Because you are using a custom controller.com/apex/StoreFront. Because this is an action. invoking a Web service. Navigate to your Visualforce page by using its URL. indicating that the table should iterate over a list called products. and so on. In this step. • • See Also: Tutorial #11: Creating a Store Front Step 2: Add Methods to the Controller Step 4: Bonus Step—Updating the Page with AJAX Step 4: Bonus Step—Updating the Page with AJAX This step is optional. There's a lot of new stuff here. {!shop}. Click the Page Editor tab.

Locate the shop() method (lines 4 through 6) and replace it with the following code. } '. The Page Editor will figure out that you don't have any method or property called “message” and offer to create it for you. 4. <apex:commandButton action="{!shop}" reRender="msg" value="Buy" /> You have now modified the Visualforce page to use an in-place AJAX update. which displays an item from the controller called "message". Click Create Apex property StoreFront.. public PageReference shop() { message = 'You bought: '.count > 0) { message += p. and click Buy. for (DisplayMerchandise p: products) { if (p. Now modify the shop() method to update the message property displayed in the panel with a list of items that were selected.count + ') } } return null.. change the commandButton tag to include a reRender attribute.name + ' (' + p. Click Save.message. 86 .merchandise. Now. Tell Me More. 5. This simple addition exposes a lot of powerful functionality. 1. <apex:outputPanel id="msg">{!message}</apex:outputPanel> You just created an output panel identified as msg. Click the Save icon. Now test the shopping cart. Modify your page by adding the following code after the </apex:form> line. indicating how many products you purchased. 4. Visualforce will automatically ensure that the data you change in the user interface is reflected by the data in the products variable. Add a number to one of the merchandise items. 3. Click the Controller tab next to the Page Editor tab. which hasn't been created yet. 2. Note: Notice how this code simply utilizes the products variable. You'll notice that a text field appears beneath the merchandise list.Tutorial #11: Creating a Store Front 3.. It updates the panel identified as "msg" after it calls the shop() method on the controller. 6.

you modified the Visualforce page to use the data passed back to the controller to display a message using an AJAX update. without refreshing the entire page. the panel updates without updating the entire screen. by either packaging for distribution or deploying it to a production organization. The AJAX effect that does this. which is outside the scope of this workbook. However. If you did the bonus step. Another thing you might want to do next is to deliver your app. so that people can log into your site. For more information. with many of the features typically found in similar languages such as Java. see Delivering Your Application on page 88. Visualforce automatically mirrored the data changes on the form back to the products variable. create a username and password. was accomplished with a simple reRender attribute. and purchase merchandise. See Also: Tutorial #11: Creating a Store Front Step 4: Bonus Step—Updating the Page with AJAX 87 . such as arrays.Tutorial #11: Creating a Store Front • • As you saw in this step.force. and querying the database. See Also: Tutorial #11: Creating a Store Front Step 3: Create the Store Front Summary Summary Apex is a powerful object-oriented language. This functionality is extremely powerful. In this tutorial you created an Apex class and used a few of the features of the language. and lets you quickly build forms and other complex input pages.com/workbook for the portal tutorial and other new additions to the workbook. which typically requires complex JavaScript manipulation. iteration. When you click the Buy button. The next thing you might do is create an authenticated portal. In order to do that. we have included detailed steps on how to create a portal that works with the app you just built. Visit developer. you'd need to create a portal.

select Sandbox from the drop-down list. You can have multiple project names on the same organization. From the Salesforce user interface. then you'll want to package it. You must reset your security token. Call this one Workbook. you'll want to know about the various ways you can deliver it. it means your current IP is not recognized from a trusted network range. d. If you are using a sandbox for development. b. Enter your password. 2. On the Project Content page click Finish to retrieve Apex and Visualforce and components. a. If you're developing this application to be installed in multiple organizations. The username is in the form of an email address.com Project. in the Environment field. then you'll deploy it.com IDE: 1. so it helps to identify each project with a descriptive name. c. 3. Delivering Your Application Now that your application is complete. Enter the username you use to log in as an administrator. Specify your organization credentials. e. 88 . If you're developing this application for just one organization.Creating a Project in the Force. Enter a project name. Note: If you get a LOGIN_MUST_USE_SECURITY_TOKEN error.com IDE To create a project in the Force. Select File ➤ New ➤ Force. click Your Name ➤ Setup ➤ My Personal Information ➤ Reset My Security Token and follow the instructions there. Click Next.com IDE APPENDIX Creating a Project in the Force.

or applications. Once an unmanaged package is installed in another organization. About Deploying If you want to deploy your code to a production organization that you have login credentials for. The Force.com/index.com AppExchange.Delivering Your Application About Packaging Packages are like suitcases that can contain your components. the publisher. code. If you prefer a graphical interface.developerforce. see wiki.com platform provides two types of packages: unmanaged and managed: • Unmanaged packages are used to distribute copies of the bundled components. there are a couple options available: • • If you're comfortable with a command-line interface.com/index. You can use them to distribute an application to multiple organizations. have no way of controlling what happens to the components that were in it. For more information. the publisher. • For more information on packaging. Managed packages are used to distribute copies of the bundled components in a way that leaves you. including all of the source code. use the Force. with control over the intellectual property and licensing.developerforce. see “Overview of Packages” in the Force. you.php/Migration_Tool_Guide.com Migration Tool for deployment.com online help. see wiki. For more information. Managed packages are the preferred way to release applications on Force. 89 . These are typically free packages without the option to upgrade.com_IDE. use the Force.php/Force.com IDE. you can also easily distribute upgrades to customers who installed older versions of the application. With managed packages.