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

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

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

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

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

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

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

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

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

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

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

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

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. and then pull it all together into an application that lets you create and track information about your merchandise. and a tab. fields.Tutorial #1: Creating a Warehouse Application Summary Congratulations! You have just built a Warehouse application that keeps track of products you have in stock. See Also: Tutorial #1: Creating a Warehouse Application Step 5: Create a Merchandise Record 13 . Although the application is far from complete. The next step is to use an invoice to track how your merchandise moves in and out of your warehouse. such as the ability to view and create merchandise.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

so you created a roll-up summary field to automatically add up the line item subtotals. and existing records with updates. but you enhanced it to work with both new records. 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. 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. You also learned how to define a validation rule to make sure you have enough items in stock. The first version of the rule was simple. An invoice could be made up of multiple line items.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.

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

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

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

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

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

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

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

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

Now that you’ve built the basic reports. Creating meaningful reports is a skill well worth learning! 37 . You also created a dashboard. which you can place on your Home tab for quick reference.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. and charts. experiment with them by modifying the filters. groupings. and a matrix report that provided a multi-dimensional analysis of your data.

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

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

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

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

42 . Then verify that its unit price is automatically set and that the total inventory on the stock has decreased. Click Check Syntax and make corrections if necessary.(Units_Sold__c . Click the Invoice Statements tab. On the Workflow Rule page. 1. Leave the Unit Price field blank.Units_Sold__c . Click Save to close the New Field Update wizard and return to Step 3 of the Workflow wizard.Total_Inventory__c . 3. Click the invoice record you created earlier. click Done. 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. Merchandise__r. 19. 17. 2. 18. On the Specify Workflow Actions page. Set Units Sold to 1000. • • • In the Line Item Number field enter 2. Select New Line Item and enter the following values.Total_Inventory__c . click Activate.PRIORVALUE(Units_Sold__c)) ) 16.Tutorial #5: Automating Processes Using Workflow Merchandise__r.

Tutorial #5: Automating Processes Using Workflow • Next to the Merchandise field. 6. Notice that the Total Inventory is down to 1000 from 2000 (or whatever you entered). 4. The workflow rule automatically updates price and inventory across different objects. 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. Now open the Wee Jet merchandise record by clicking on the Wee Jet link. Click Save. and then sends an email alert to the designated recipient. The approval process runs whenever a condition is met. Click line item 2. Note that the unit price has been set to the same value as on the Wee Jet record. 5. 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 .

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

In the Profile field. The Username field defaults to your email address. 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. 4. Click Your Name ➤ Setup ➤ Create ➤ Workflow & Approvals ➤ Approval Processes. Click Save. 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 User License field. select Basic User. enter Large Invoice Value. enter bsmith. but you'll need to create a unique username for Bob. In the Manage Approval Processes For drop-down list. In the Name field. Click Create New Approval Process and choose Use Jump Start Wizard from the drop-down list. In the Email field. because you'll be logging in as him shortly. Note: Write down Bob's username (his imaginary email address). 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. 3. enter Smith.Tutorial #6: Creating an Approval Process • • • • In the Last Name field. select Salesforce. 45 . in the form of an imaginary email address. select the user you created when you signed up for your organization. enter your own email address. 1. 2. In the Alias field. so that you will receive the approval requests routed to Bob Smith. choose Invoice Statement. 4. • • • In the Manager field.

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

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

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

and the actions that need to be taken. but you can change the conditions for when an approval process runs.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. This email alert was a fairly simple example. See Also: Tutorial #6: Creating an Approval Process Step 5: Test the Approval Process 51 .

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

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

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

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

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

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

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

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

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

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

ideally you should also check all possible scenarios. It should also check other status values. then raising or lowering the price shouldn't have any effect. if an invoice statement does not have a status of Negotiating. See Also: Tutorial #8: Adding Tests to Your Application Step 5: View Code Coverage and Improve Tests 64 . and the test case you have just written misses one. Right now it only checks invoice statements that have a status of Negotiating.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. But it's important to note that code coverage isn't the only goal for testing. For example. Creating unit tests as you develop is necessary for deployment and it's also the key to successful long-term development.

The purpose of the count sheet is to update the computer system with a physical count of the merchandise. It allows you to see code and preview the page at the same time. 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. and an Apex-based controller model.com platform. 65 . Click Edit. a library of reusable components that can be extended. 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.Tutorial #9: Building a Custom User Interface Using Visualforce Tutorial #9: Building a Custom User Interface Using Visualforce Level: Intermediate. Visualforce supports the Model-View-Controller (MVC) style of user interface design. it helps to have basic knowledge of markup languages like HTML and XML. Duration: 30–45 minutes Visualforce is a component-based user interface framework for the Force. In previous tutorials you built and extended your application by using a user interface that is automatically generated. but it is not required. in case they are different. Click Your Name ➤ Setup ➤ My Personal Information ➤ Personal Information. 1. Prerequisites Basic Knowledge For this tutorial. 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. In this tutorial. 2. 3. Development Mode also adds an Apex editor for editing controllers and extensions. Select the Development Mode checkbox and click Save. and is highly flexible. as well as update the counts on each.

salesforce. 66 . It should look like this. In your browser. Click the Page Editor link in the bottom left corner of the page. add the text /apex/CountSheet to the URL for your Salesforce instance. if your Salesforce instance is https://na1.com. For example. You will get an error message: Page CountSheet does not exist. 1.salesforce. the new URL would be https://na1.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. 2. Click the Create Page CountSheet link to create the new page. The Page Editor tab displays the code and a preview of the new page (which has some default text). 3.com/apex/CountSheet.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Sign up to vote on this title
UsefulNot useful