Force.

com Workbook: Winter '11

Force.com Workbook

Last updated: November 6, 2010
© Copyright 2000-2010 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..................................................................................................................................................................9 Step 4: Create a Warehouse App.............................................................................................................................................10 Step 5: Create a Merchandise Record.....................................................................................................................................11 Summary.................................................................................................................................................................................12 Tutorial #2: Adding Relationships......................................................................................................................................................13 Step 1: Create an Invoice Statement Custom Object..............................................................................................................13 Step 2: Create a Line Item Object...........................................................................................................................................16 Step 3: Relate the Objects.......................................................................................................................................................17 Step 4: Add Invoice Statements to the App............................................................................................................................18 Step 5: Create an Invoice Record............................................................................................................................................18 Summary.................................................................................................................................................................................20 Tutorial #3: Using Formulas and Validation Rules..............................................................................................................................21 Step 1: Calculate a Value for Each Line Item..........................................................................................................................21 Step 2: Calculate a Value for the Invoice Statement With a Roll-Up Summary Field............................................................22 Step 3: Check Inventory With a Validation Rule....................................................................................................................23 Step 4: Test the Validation Rule..............................................................................................................................................25 Step 5: Improve the Validation Rule........................................................................................................................................25 Summary.................................................................................................................................................................................26 Tutorial #4: Using Workflow and Approvals.......................................................................................................................................28 Step 1: Populate the Line Item Price Using a Workflow Rule................................................................................................28 Step 2: Update Total Inventory When an Order is Placed......................................................................................................30 Step 3: Test the Workflow Rules.............................................................................................................................................32 Step 4: Create an Email Template...........................................................................................................................................33 Step 5: Create an Approval Process.........................................................................................................................................34 Step 6: Create a Custom Profile..............................................................................................................................................36 Step 7: Create a User...............................................................................................................................................................37 Step 8: Test the Approval Process............................................................................................................................................38 Summary.................................................................................................................................................................................40 Tutorial #5: Adding Business Logic with Apex..................................................................................................................................41 Step 1: Create an Apex Trigger Definition..............................................................................................................................42 Step 2: Define a List Variable..................................................................................................................................................43 Step 3: Iterate Through the List and Modify Price.................................................................................................................44 Step 4: Test the Trigger...........................................................................................................................................................45 Summary.................................................................................................................................................................................46 Tutorial #6: Adding Tests to Your Application....................................................................................................................................47 Step 1: Create an Apex Test Class...........................................................................................................................................47 Step 2: Add Test Methods to the Class...................................................................................................................................48

i

............................................................................................................................................................................................................................95 ii ..................................................................................53 Tutorial #7: Building a Custom User Interface Using Visualforce..............................................................................................................................................................................................................................................................................................................................................................................................................................com Flex.............................................................................................................................................................................................59 Summary......................................................................................................................................................55 Step 3: Add a Stylesheet Static Resource......................................................................94 Creating a Project in the Force.................................................................71 Step 4: Bonus Step—Updating the Page with AJAX........................................................................................................................................com Domain Name..............................................................................................56 Step 4: Add a Controller to the Page......................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................67 Tutorial #9: Creating a Store Front.................................................................................................75 Step 1: Configure Your Salesforce..................................................................................................90 Summary................................com Flex Project....................................................................................................................................................................................94 Creating and Logging into a Sandbox.......................................................................................................................................................................................................93 Appendix.................................................................................................................................................................77 Step 3: Generate Your Enterprise WSDL...................................................................................com Personal Information.................................................................................................................................................76 Step 2: Create an Offline Briefcase Configuration...........................................................................................94 Delivering Your Application..................................................................68 Step 2: Add Methods to the Controller..........................................................................................................................................68 Step 1: Create a Controller...........................................................72 Summary........................................................................................................................80 Step 6: Import Your Enterprise WSDL...................................................................64 Step 3: Create a Force............................................................................................................................................................................................................com Flex......62 Step 2: Register a Force.........................51 Summary.....69 Step 3: Create the Store Front.............................................................Table of Contents Step 3: Write Code to Execute the Trigger..................61 Tutorial #8: Creating a Public Web Page Using Sites................................................................................................................................................74 Tutorial #10: Creating a Desktop App with Force.......................................................................................................................................................................................50 Step 5: View Code Coverage and Improve Tests....................................................................79 Step 4: Install and Launch Force................................84 Step 9: Testing the Inventory Tracker application...............................................................79 Step 5: Create a Force.....................54 Step 2: Create a Visualforce Page..........................................................................................................................................................................65 Summary.....................................com Site..................com Flex Application Component Attributes.......................62 Step 1: Create a Product Catalog Page......................54 Step 1: Enable Visualforce Development Mode.....49 Step 4: Execute the Test..........82 Step 7: Set the Force.....................65 Step 4: Configure and Test the Site............................................................................................................................................................................................................83 Step 8: Create the Inventory Tracker Window Component................58 Step 5: Display the Inventory Count Sheet as a Visualforce Page...............................................................com IDE........................................................................

jsp. How is the Workbook Organized? The tutorials in this workbook build on one another and are designed to be done in order. If you have not created a sandbox yet.com Workbook shows you how to create an application in a series of tutorials.com platform to build virtually any kind of application. However. we've added a final tutorial to use Force.com Flex. which has all of the required features and functionality.force. When you complete the application. a public website to display a product catalog. You can't use Free Edition to complete Tutorial #10: Creating a Desktop App with Force. but it's all quite easy—as you'll soon see. Each of the tutorials builds on the previous tutorial to advance the application's development and simultaneously showcase a particular feature of the platform. To sign up for a free Developer Edition organization. see Delivering Your Application on page 95.com Workbook About the Force. To sign up for a Free Edition organization. For example. For more information. In most cases. navigate to salesforce. It may sound like a lot. you can also use Free Edition with the following considerations. The pictures in the workbook may be slightly different from what you see on your screen. While you can use the Force. You'll start developing the application from the bottom up. approvals to send email notifications for large invoice values. see Creating and Logging into a Sandbox on page 94.com Flex. If you'd like to develop offline and integrate with the app. 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. you'll create a user interface to display a product inventory to staff. Force. while Free Edition has a Getting Started tab. 3 . you can migrate the changes from your sandbox to production. these differences are trivial.com/form/signup/freeforce-platform. and trigger logic to update the prices in open invoices. Developer Edition uses a Start Here tab.com Flex is only available in Developer Edition. you'll first build a database model for keeping track of merchandise. Once the database and business logic are complete. navigate to developer.About the Force. As a developer preview. and then the start of a simple store front. workflow to update inventory when something is sold. Choosing a Development Environment This workbook is designed to be used with a Developer Edition organization.com Workbook The Force.com/join. You'll continue by adding business logic: validation rules to ensure that there is enough stock. • • • • Some of the tutorials require that you use a sandbox. so it's easiest if you complete all of the tutorials within your sandbox organization. that is.

com Workbook Tutorial Create the App Tutorial #1: Creating a Warehouse Application Tutorial #2: Adding Relationships Add Logic Tutorial #3: Using Formulas and Validation Rules Tutorial #4: Using Workflow and Approvals Tutorial #5: Adding Business Logic with Apex Write Tests Tutorial #6: Adding Tests to Your Application Extend the User Interface Tutorial #7: Building a Custom User Interface Using Visualforce Tutorial #8: Creating a Public Web Page Using Sites Tutorial #9: Creating a Store Front Offline Integration Tutorial #10: Creating a Desktop App with Force. • • To learn more about Force.com Flex Appendix Creating and Logging into a Sandbox Creating a Project in the Force.force.About the Force. However. there's a lot of useful information here and some additional steps to flesh out your app.com IDE Delivering Your Application Difficulty Estimated Time to Complete Beginner Beginner 20-30 minutes 20-30 minutes Beginner Intermediate Advanced 20-30 minutes 30-45 minutes 20-30 minutes Advanced 20-30 minutes Intermediate Intermediate Intermediate 30–45 minutes 20-30 minutes 30 minutes Advanced 30 minutes Tell Me More. move on to the next step.com. 4 . At the end of each step there is an optional Tell Me More section... if you're a smell-the-roses type. visit Developer Force at developer. If you like to do things quickly.force..com and to access a rich set of resources. You can find the latest version of this Workbook and additional tutorials that extend the app at developer.com/workbook.

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

the detail page for the custom object opens. Click New Custom Object to display the New Custom Object wizard. Leave all other values as they are. 6 . Tell Me More. Click Save to finish creating your new object. Fill in the custom object definition.. Take a look at the following image to familiarize yourself with the Merchandise custom object.Tutorial #1: Creating a Warehouse Application 4. After you save the new custom object. For the Plural Label. • • • For the Label. 5. enter Merchandise.. enter Merchandise.. 6.

Price. Soon you'll be adding fields. a. You can add custom fields to list or track just about anything you can think of. which means it will automatically track who created each record. and Total Inventory Fields Step 2: Add Description. validation rules. Create the Description field.Tutorial #1: Creating a Warehouse Application 1. you didn't specify an API name. API name—When you created the Merchandise object. which differentiates them from standard objects and makes them easier to identify. See Also: Tutorial #1: Creating a Warehouse Application Step 2: Add Description. how much it costs. Merchandise detail page—This page shows you everything you need to know about your Merchandise custom object. and how many are in stock. c. 2. and inventory. 3. Click New to launch the New Custom Field wizard. such as a description. select Text Area and click Next. b. but one is generated for you. Scroll down to the Custom Fields & Relationships related list. and Total Inventory Fields A merchandise object should have fields that are used for tracking various information. you're right. Follow the steps below to create custom fields for the description. For example. relationships. these are called standard fields. Custom fields—You haven't defined any custom fields yet. 7 . 1. For Data Type. the Merchandise object has a standard field for Owner. price. and other neat features to this custom object. This name is how you reference the object programmatically. Price. If you guessed that custom fields have names that end in __c. 4. All custom objects end in __c. Standard fields—Some fields are generated automatically. you'll do that in the next step.

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

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

From the Object drop-down list. Click New to launch the New Custom App wizard. See Also: Tutorial #1: Creating a Warehouse Application Step 2: Add Description. In this step you create a Warehouse application and add a tab to it. As soon as you create the tab. 3. When you create a tab. select Merchandise..Tutorial #1: Creating a Warehouse Application 3. 4. you'll add more tabs to the app. 1. 2. you can choose your own color and custom image by clicking Create your own style. • For the App Label. For the Tab Style. Price. Later.. enter Warehouse. click the lookup icon and select the Box icon. 6. and Total Inventory Fields Step 4: Create a Warehouse App Step 4: Create a Warehouse App An application is a set of tabs. you're not stuck with a standard set of icons and colors. Navigate to Your Name ➤ Setup ➤ Create ➤ Apps. Accept the remaining defaults. and click Next. 10 . Click Next and then Save to finish creating the tab. Tell Me More. you can see it at the top of the screen. 5. Fill in the custom app details.

5... and delete records. the platform automatically generates a user interface that lets you create. 7. When you define an object on Force. In fact. Accept the defaults on the next page. Click Next. Click Save to create the Warehouse application. enter Warehouse. 4. read. 8. Now check to see how your new application works. For example. Leave the Default Landing Tab set to the Home tab. 6.com. In the Available Tabs list. and click Next. 9. 11 . locate the Merchandise tab and click Add to add it to the list of selected tabs. and click Next. You can switch between applications you have created.com app menu in the upper right corner of the page. you can add that to the Warehouse app. 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. you can modify custom applications to group all of your most frequently used tabs together in one place.Tutorial #1: Creating a Warehouse Application • For the App Name. Select the Visible checkbox to make the application available to all user profiles. The tabs in an application don't have to be related to each other. bought. update. or installed by simply selecting any one of them from the menu. Tell Me More. if you refer to the Start Here tab a lot. As soon as you create the application. it appears in the Force. using the default logo for the app..

Your warehouse will work just fine with only one product. Tip: use Save and New to create new records rapidly. Although the application is far from complete..99. Tell Me More.. In the Total Inventory field enter 2000. Select the Warehouse application from the Force. For Description field enter A small plane. As you can see. Click Save. Go ahead and create some more. 3. such as the ability to view and create merchandise. In the Price field enter 9. See Also: Tutorial #1: Creating a Warehouse Application Step 5: Create a Merchandise Record 12 . See Also: Tutorial #1: Creating a Warehouse Application Step 4: Create a Warehouse App Summary Summary Congratulations! You have just built a Warehouse application that keeps track of products you have in stock.com app menu.Tutorial #1: Creating a Warehouse Application 1. Fill in all the fields. it already has a lot of built-in functionality. fields. but it would be more realistic if you had more merchandise. • • • • In the Merchandise Name field enter Wee Jet. 2. as shown in the following image. and a tab. 4. Click the Merchandise tab and then click New to create a new product. The next step is to use an invoice to track how your merchandise moves in and out of your warehouse. it's easy to use the online interface and wizards to create a custom object.. and then pull it all together into an application that lets you create and track information about your merchandise.

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

Open Closed Negotiating Pending • Select the checkbox for Use first value as default value. c. Enter the following picklist values in the box provided.Tutorial #2: Adding Relationships • In the Starting Number field. b. 3. Scroll down to the Custom Fields & Relationships related list and click New. 14 . Fill in the custom field details. • • In the Field Label field . Add a Status field. 4. Leave all other values as they are and click Save. each entry on its own line. a. enter 1. For Data Type. select Picklist and click Next. enter Status.

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

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

You also created two custom fields that have system-generated values: the Status picklist. In the Field Label field. accepting the defaults. numbers. All of those fields have something in common: the values are provided by the user. 7. scroll down to the Custom Fields & Relationships related list and click New. 2. which is automatically assigned by the Auto-number data type. In the Related To field. Tell Me More. 5.. In the next step you will create two more fields. these get their values from other objects. On the detail page of the Line Item object. Master-detail relationships also support roll-up summary fields. enter Units Sold and click Next. See Also: Tutorial #2: Adding Relationships Step 2: Create a Line Item Object Step 4: Add Invoice Statements to the App 17 ..Tutorial #2: Adding Relationships a. and that the Invoice Line Items are related to Merchandise. In the Data Type field. 4. Click Save to return to the detail page of the Line Item custom object. select your Merchandise custom object and click Next. Click Next. and Line Item. Accept the defaults on the next three screens by clicking Next. and currency. You have just created two master-detail relationships ensuring that your Invoice Statement records are related to Invoice Line Item records. b. which defaults to Open. and then click Save to return to the Inventory Item detail screen.. 3. 1. 8. In the Data Type field. select your Invoice Statement custom object and click Next. Click Save & New. and the Invoice_Number field.. You'll use that feature in a later tutorial. Deselect the checkbox next to Merchandise Layout so that Line Items don't appear on the Merchandise related list. 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. c. 9. Tell Me More. select Master-Detail Relationship and click Next.. In the Related To field. allowing you to aggregate information about the child records. 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). In the Data Type field. select Master-Detail Relationship and click Next. On each of those objects you created custom fields to represent text. At this point you've created three custom objects: Merchandise. Unlike the previous fields. you want to relate them to each other. select Number and click Next.. d. 6. Inventory Statement. Accept the defaults on the following screens by clicking Next.

click New to launch the New Custom Tab wizard. click Create ➤ Tabs. This will expose the user interface that Force. In the Custom Object Tabs related list.com automatically generates for this object. 6. 1. 4. 5. 3. you'll want to create a tab for the Invoice Statement object and add it to your Warehouse app. enter First Invoice and then click Save. edit. 2. 18 . so that you can view. From the Object drop-down list. 7. the platform automatically generates a user interface for the objects you create. select Invoice Statement. 1. Because you also related the objects. Accept the remaining defaults. delete. Click the Invoice Statements tab. for the Merchandise custom object.Tutorial #2: Adding Relationships Step 4: Add Invoice Statements to the App Just as you did before. 3. The detail page of your invoice statement should look like this. This will add the Invoice Statements tab to your Warehouse app. Your Invoice Statements tab is now part of your app. and update records. Click Save to finish creating the tab. In the Description field. For the Tab Style. click the lookup button and select the Form icon. On the Add to Custom Apps page. 2. the user interface provides a way of navigating between related records as well. Click New. 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. and click Next and then Next again. Within the Setup area. deselect all the checkboxes except Warehouse.

• • • • In the Line Item Number field enter 1. Fill in the fields. and this tutorial is supposed to be easy. Tell Me More. In the Units Sold field. 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. You can make Line Item an auto number field if you want to.. and how the user interface displays an empty Line Items related list below it.. but it makes a later tutorial. like Invoice Statements? The short answer is that it's easier to work with text when we work with records. 2.. Click Save. when what you enter is a number. You might be wondering why Line Item Number is a text field. If line items are numbered. 3. For the Merchandise field. Click New Line Item. a bit more difficult. why not make it an auto-number field. Tutorial #8: Creating a Public Web Page Using Sites. 1.Tutorial #2: Adding Relationships Notice how the invoice was automatically assigned a number. See Also: Tutorial #2: Adding Relationships Step 4: Add Invoice Statements to the App Summary 19 . Next you'll add a line item to the invoice. click the lookup button and select a product. In the Unit Price field enter 10. enter 4.

and in the next tutorial you'll see how to sum the price of each invoice line item into the invoice statement. yet they operate at a more abstract level. See Also: Tutorial #2: Adding Relationships Step 5: Create an Invoice Record 20 . Now that you have built the basic application. You'll learn about that later as well. letting you concentrate on what matters (the relationships) instead of the underlying implementation.Tutorial #2: Adding Relationships Summary In this tutorial. The relationships work like foreign keys in relational databases. The master-detail relationship allows you to aggregate information. The relationships also provide additional benefits: you can navigate to the related records in a user interface and a query language. you can add business logic with formulas and validation rules in Tutorial #3: Using Formulas and Validation Rules on page 21. you created relationships between the objects in your data model.

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

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

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

fix them before proceeding. then choose Units Sold from the drop-down list.Total_Inventory__c—This tells the system to retrieve the value of Total Inventory field on the related Merchandise record.. Let's analyze the formula you created. In the Error Message field. Tell Me More. 6. Type the less-than symbol < so that the formula looks like this: Merchandise__r. For the Error Location. 8. Click Check Syntax to make sure there are no errors. Click Insert Field again.Total_Inventory__c < Units_Sold__c 5.Tutorial #3: Using Formulas and Validation Rules e. enter You have ordered more items than we have in stock. you can easily traverse the available objects and find the components you need for the formula. i. 7. Units_Sold__c—This refers to the Units Sold field on the current (Line Item) record. Merchandise__r. select Field.. You can enter a formula directly into the Error Condition Formula area. Merchandise__r. Click Insert and verify the code looks like the following. g. • Mechandise__r—Because the Merchandise object is related to the Line Item object. Click Save.. Select Line Item > in the first column. the platform automatically provides a relationship field that lets you navigate from a Line Item record to a Merchandise record. but as you saw here. Select Units Sold in the second column. If you do find errors. 24 . h. that's what the Mechandise__r is doing. • • • Total_Inventory__c—This is the field you created to track the total amount of stock on a Merchandise record.Total_Inventory__c < f.

5. Click on the Invoice Statements tab and select an existing invoice. See Also: Tutorial #3: Using Formulas and Validation Rules Step 3: Check Inventory With a Validation Rule Step 5: Improve the Validation Rule 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. You can improve the validation rule to include these scenarios by using the ISNEW() function in your formula.Tutorial #3: Using Formulas and Validation Rules Putting it all together. Click Cancel. you shouldn't need to check inventory. 1. In this case. As indicated on the Error Condition Formula page. 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. which determines whether you are creating a new record. you'll need to use the PRIORVALUE() function to tell you the prior value of the field before it was modified. 3. You should see an error indicating that there are not enough items in stock. 25 . Scroll down to Line Items and click Edit next to one of the line items. you need to provide a formula that is true if an error should be displayed. Or if you increased the number of units sold. Click Save. 4. If it's not a new record. Click Cancel. the formula checks that the total inventory on the related merchandise record is less than the number of units being sold. and this is just what you want: it will only be true when the total inventory is less than the units sold. 2. Modify the Units Sold value to a number larger than the amount in stock. you should only need to verify that the number of additional items is in stock.

then you simply check inventory as you did previously. IF ( Units_Sold__c < PRIORVALUE(Units_Sold__c). 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.Total_Inventory__c < Units_Sold__c . • • • • IF is a conditional.PRIORVALUE(Units_Sold__c)) ) ) 4. Merchandise__r. If ISNEW is false. by comparing it to its prior value using the PRIORVALUE function. See Also: Tutorial #3: Using Formulas and Validation Rules Step 4: Test the Validation Rule Summary Summary In this tutorial you created formula fields and validation rules that enhance and validate your app's data. then you've increased the number of units. 3. you know that you're performing an update to an existing record. Scroll down to the Validation Rules related list.. Tell Me More. so you have to check whether there's enough inventory to hold the difference between the new number of units and the old.Tutorial #3: Using Formulas and Validation Rules 1. ISNEW is the condition. Since you have enough stock. ensuring that at run time one of the two branches will be taken depending on the condition. This function returns true if you're creating a new record. Navigate back to the Line Item custom object page by clicking Your Name ➤ Setup ➤ Create ➤ Objects ➤ Line Item. and next to Order in stock click Edit... For new records. this time to determine if the number of units has gone up or down. FALSE. 5. If ISNEW is true. Merchandise__r. you return FALSE to indicate that there's no validation failure. not creating a new record. If the prior value was greater.Total_Inventory__c < (Units_Sold__c . An invoice could be made up of multiple line items. so you perform another conditional check. If the prior value was smaller. IF( ISNEW(). 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. so you created a roll-up summary field to automatically add up the line item subtotals. 26 . Click Save. false otherwise. 2. Click Check Syntax to make sure there are no errors. then you've updated the record and decreased its units. Replace the existing formula with the following.

and existing records with updates.Tutorial #3: Using Formulas and Validation Rules You also learned how to define a validation rule to make sure you have enough items in stock. 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 27 . The first version of the rule was simple.

28 . Workflow rules can trigger actions (such as email alerts. See Also: Step 1: Populate the Line Item Price Using a Workflow Rule Step 2: Update Total Inventory When an Order is Placed Step 3: Test the Workflow Rules Step 4: Create an Email Template Step 5: Create an Approval Process Step 6: Create a Custom Profile Step 7: Create a User Step 8: Test the Approval Process Summary Step 1: Populate the Line Item Price Using a Workflow Rule At this point. The first carries the current price of a merchandise item into the newly created line item record. field updates. tasks. In this tutorial. Not only do they save time. You've also marked the Line Item Price field as read-only.Tutorial #4: Using Workflow and Approvals Tutorial #4: Using Workflow and Approvals Level: Intermediate. 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. criteria. Approval processes can automate all of your organization's approvals—from simple to complex. you can use workflow rules and approval processes to automate your procedures and processes. You can create this complex logic quite easily with a declarative workflow rule. you create and test two workflow rules. they also enforce consistency and compliance within your company's business practices. and formulas.com app. 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 21. who has access to all data. and outbound messages) based on time triggers. Duration: 30-45 minutes Your company can operate more efficiently with standardized internal procedures and automated business processes. you've created the Line Item and the Merchandise objects with Price fields. and the second updates the inventory whenever you update a product line item. You will also create an approval process that requires explicit approval from the manager if an invoice is over $2000. In your Force. though you probably didn't notice that in the user interface because your default user is an administrative user.

Make sure your page looks like the following and then click Save & Next. 13. In Step 1 of the Workflow Rule wizard. 16. In the Rule Name field. Click Insert. 10. In the text box. 4.Tutorial #4: Using Workflow and Approvals 1. enter Insert Merchandise Price. In the Name field. 8. For Evaluation Criteria. Click Insert Field. In the Rule Criteria field. If you see the Understanding Workflow page. 29 . Click Show Formula Editor. and Price in the third column. select formula evaluates to true. Select Line Item > in the first column. Click Your Name ➤ Setup ➤ Create ➤ Workflow & Approvals ➤ Workflow Rules. 7. 9. select Line Item in the first box and Unit Price in the second. select Only when a record is created. Select Use a formula to set the new value. 6. In the Field to Update drop-down list. 15. Merchandise > in the second column. In Step 3 of the Workflow Rule wizard. enter true. 3. select Line Item as the object and click Next. 14. 11. enter Line Item Created. The New Field Update wizard opens. 5. in the Immediate Workflow Actions section. click New Rule. On the All Workflow Rules page. 2. click Continue. 12. click Add Workflow Action and choose New Field Update.

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

3. Click Insert Selected.Total_Inventory__c . If you see the Understanding Workflow screen. 15. In Step 1 of the Workflow Rule wizard. click Continue. 2. Click Check Syntax and make corrections if necessary. otherwise proceed to the next step. For Evaluation Criteria select Every time a record is created or edited.(Units_Sold__c . click Add Workflow Action and choose New Field Update. In the Rule Criteria field. select Line Item as the object and click Next. The New Field Update wizard opens.Total_Inventory__c . click New Rule. In the second. Click Show Formula Editor. 8. In the Field drop-down list. 4. 9. Enter the following code. you need to decrease the total inventory by the number of units sold. But if you're updating a line item. select Invoice Statement: Status. enter Update Stock Inventory. enter Line Item Updated. 11.Tutorial #4: Using Workflow and Approvals total inventory value. 13.Units_Sold__c . In the Rule Name field. Then for Operator. in the Immediate Workflow Actions section. In Step 3 of the Workflow Rule wizard. 12. select Total Inventory.PRIORVALUE(Units_Sold__c)) ) 16. In the Name field. you need to adjust the total inventory by the difference between the numbers of old and new units sold. Select Use a formula to set the new value. Click Your Name ➤ Setup ➤ Create ➤ Workflow & Approvals ➤ Workflow Rules. 7. On the All Workflow Rules page. Merchandise__r. select equals. Merchandise__r. select Merchandise. Make sure your screen looks like the following and then click Save & Next. 14. 6. If you're creating a new line item. 5. In the first Field to Update drop-down list. Under Value click the lookup icon and choose Open. 31 . select criteria are met. 1. 10. IF ( ISNEW().

Click the Invoice Statements tab. 1. On the Workflow Rule page. click the lookup icon and select the Wee Jet merchandise record. Click the invoice record you created earlier. 32 . Click line item 2. Set Units Sold to 1000. 18. 5. Select New Line Item and enter the following values. • • • • In the Line Item Number field enter 2. 19. See Also: Tutorial #4: Using Workflow and Approvals Step 1: Populate the Line Item Price Using a Workflow Rule Step 3: Test the Workflow Rules Step 3: Test the Workflow Rules You can check to make sure your workflows are functioning as expected by creating a new line item. click Done. Click Save. 4. 2. click Activate. 3. Click Save to close the New Field Update wizard and return to Step 3 of the Workflow wizard.Tutorial #4: Using Workflow and Approvals 17. Note that the unit price has been set to the same value as on the Wee Jet record. Next to the Merchandise field. Leave the Unit Price field blank. Then verify that its unit price is automatically set and that the total inventory on the stock has decreased. On the Specify Workflow Actions page.

6. Verify that your screen looks like the following. In the Email Template Name field. enter the following code and text. Click New Template.Tutorial #4: Using Workflow and Approvals 6.LastModifiedDate} 8.OwnerFullName} submitted for approval an Invoice Statement that totalled {!Invoice_Statement__c. and then click Save.Invoice_Value__c} on {!Invoice_Statement__c. In the Subject field. enter Large Invoice Template. In this step you create the email template that will be used by the workflow rule to generate and send the email. Now open the Wee Jet merchandise record by clicking on the Wee Jet link. 5. 3. 2. Notice that the Total Inventory is down to 1000 from 2000 (or whatever you entered). Click Your Name ➤ Setup ➤ Communication Templates ➤ Email Templates. enter A large invoice has been submitted. 4. 1. 33 . {!Invoice_Statement__c. and an approval process for the manager to follow. You create the approval process in the next steps. just assume we're talking about whatever currency you're using. Note: If your default currency is not set to US dollars. select Text and click Next. See Also: Tutorial #4: Using Workflow and Approvals Step 2: Update Total Inventory When an Order is Placed Step 4: Create an Email Template Step 4: Create an Email Template One of the business rules that you want to enforce in your workflow is that all invoices totaling over $2000 must be approved by a manager. To implement this rule you need to create two additional elements: an email to be sent to the manager when an invoice exceeds $2000. In Step 1 of the Email Template wizard. Select Available For Use. In the Email Body field. 7.

The email body text that you just entered supports merge fields. 7. Click Create New Approval Process and choose Use Jump Start Wizard from the drop-down list. the user's manager is assigned as the approver. for example {!Invoice_Statement__c. You'll create a user named Bob Smith in the next step. b. In the Operator drop-down list.Tutorial #4: Using Workflow and Approvals Tell Me More. choose greater than. Enter the following values in the Specify Entry Criteria area. Next to the Approval Assignment Email Template field. See Also: Tutorial #4: Using Workflow and Approvals Step 3: Test the Workflow Rules Step 5: Create an Approval Process Step 5: 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. click the lookup icon and select the Large Invoice Template you just created. Click Your Name ➤ Setup ➤ Create ➤ Workflow & Approvals ➤ Approval Processes. This ensures that if a particular user starts the approval process. 2. 3. In the Name field.. c. choose Invoice Value. enter Large Invoice Value. 34 . Creating and using an approval process is just as easy as creating a workflow rule. In the Manage Approval Processes For drop-down list. In the Field drop-down list. 5. a. 1. Select Automatically assign an approver using a standard or custom hierarchy field and choose Manager for the hierarchy field. 6.. In the Value field enter 2000. 4..Invoice_Value__c}. At the time the email is generated. this value will be dynamically substituted with the actual invoice value that generated the approval process. choose Invoice Statement.

you have to define what happens to records when they're first submitted. Click Activate to activate the approval process. 14. Click Save. Set Initial Approval Status Status Set Final Approval Status Set Final Rejection Status Status Status 12. Configure each field update action as shown. Click Approval Processes to return to the approval list. Choose A specific value and select Open.Tutorial #4: Using Workflow and Approvals 8. when they're approved. 11. 13. Create new field update actions by clicking Add New and selecting Field Update for each related list in the following table. 9. Click View Approval Process Detail Page. You'll see a warning that you must activate the approval process. Click Save. Related List Initial Submission Actions Final Approval Actions Final Rejection Actions Name Field to Update Picklist Options Choose A specific value and select Pending. Click OK. Choose A specific value and select Closed. and when they're rejected. 10. but before it can run. You've finished creating the approval process. 35 .

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

you can grant read-only access to fields to a certain group of users. You can also strictly enforce data sharing..com application.. In the User License field. 37 . you can use enhanced profile list views to create a custom list view of your profiles and then edit the profiles from the list. the invoice is routed to his or her manager. enter bsmith. You use this configuration to make sure that if the new user creates an invoice that meets certain conditions. 1. it's automatically enabled to allow multiple users to log in. enter Bob. For more information. Note: Write down Bob's username (his imaginary email address). See Also: Tutorial #4: Using Workflow and Approvals Step 5: Create an Approval Process Step 7: Create a User Step 7: Create a User When you create a Force. In the Alias field. You've just seen how easy it is to create and edit a custom profile. In the Last Name field. enter your own email address.Tutorial #4: Using Workflow and Approvals Tell Me More. because you'll be logging in as him shortly. • • • In the Manager field. Now you can customize the application by configuring it to function differently depending on the profile of the user logging in.. In this step. click New User. 3. The Username field defaults to your email address. If you need to edit many profiles. On the All Users page. 2. enter Smith. Click Your Name ➤ Setup ➤ Manage Users ➤ Users. but you'll need to create a unique username for Bob. see “Editing Profiles Using Profile Lists” in the Salesforce. so that you will receive the approval requests routed to Bob Smith. select Basic User. select the user you created when you signed up for your organization. In the Email field. or make them completely invisible. you create a new user and link that user to your current user's account via the Manager field. In the Profile field. select Salesforce. so that a user sees only his or her records or those of his or her manager. Enter the following information: • • • • • In the First Name field. in the form of an imaginary email address. For example.com online help.

click Edit. If Bob Smith creates an invoice. Next to the Basic User profile. you want its status updated to Closed. if it is not already selected. and the total value of the invoice is greater than $2000. You should now receive an email confirming the creation of the new user. skip this step. he will be able to click the new Submit for Approval button on the invoice statement. you have to modify the Basic User profile to use the Warehouse app. click Edit next to VolunteerForce Home Page. (If you're using Free Edition. select Default. 2. In Free Edition. so don't log in as Bob Smith yet or you'll have to immediately log back in as the administrator.Tutorial #4: Using Workflow and Approvals 4. In a real-world scenario. 4. Click Your Name ➤ Setup ➤ Customize ➤ Home ➤ Home Page Layouts. 2. so it must be the default. 38 . 3. Click Next. Click Save. 1. Free Edition users only get access to one app.) 3. If the manager approves the invoice. make sure that your Home page can display items that require approval. preventing Bob from making any more changes. you want it to remain in the original Open status. The app will send an email to his manager (using the email template you created earlier) and lock the record. (If you're using Developer Edition. When the manager logs in. Next to Warehouse. Click Edit next to your home page layout. and so on. And if not.) 1. There's one more setup step to complete the approval process. Click Your Name ➤ Setup ➤ Manage Users ➤ Profiles. Before testing the approval process. your business process might require you to email the invoice owner and ask for confirmation. Select the Items to Approve option. See Also: Tutorial #4: Using Workflow and Approvals Step 6: Create a Custom Profile Step 8: Test the Approval Process Step 8: Test the Approval Process We can now put the approval process together and see it in action. he or she can approve (or reject) the invoice. before Bob can login and use the Warehouse app. and then click Save.

you see the pending approval request on the Home tab. you can check your email to verify this result. 5. you can see a nice diagram of the approval process and the actions that will fire at each step. 8. Log out of the application. When you log in to the application as administrator. In the familiar Your Name ➤ Setup area. the user you created earlier. From your Approval Process detail page. Click Save. Click New and create an invoice statement. 1. Click Submit for Approval. Add a New Line Item and enough units sold to make the invoice value greater than $2000. 1. (You may have to scroll down to see it. 3.. Select the Warehouse app. 6. Go ahead and Approve it. 2.. An email is sent to Bob Smith's designated manager who. Click View Diagram. Log in as Bob Smith. Tell Me More. 7. you need to log out of your administrator account and log back in as a standard user. you may have to change your password. Click the Invoice Statements tab. you've been logged in as an administrator.Tutorial #4: Using Workflow and Approvals While developing the application. is you the administrator.) The record is locked until the manager approves the invoice. 39 . If this is your first time logging in as Bob. To create a new record and test the approval process.. An Approval field allows the manager to approve or reject the invoice and continue the workflow. 4. Since you're the manager. click Approval Process and select the process you created. The approval process diagram appears in a separate browser window. 2. for purposes of this tutorial.

The approval process runs whenever a condition is met. follow the instructions in Creating and Logging into a Sandbox on page 94. The workflow rule automatically updates price and inventory across different objects. Your sandbox copy won't duplicate your existing records for you. Important: If you're using Free Edition. If you're not developing in a sandbox now. so after you log in. See Also: Tutorial #4: Using Workflow and Approvals Step 8: Test the Approval Process 40 . and then sends an email alert to the designated recipient. and the invoice statement described in Step 5: Create an Invoice Record on page 18. you need to recreate the Wee Jet record described in Step 5: Create a Merchandise Record on page 11. the remaining tutorials require that you develop in a sandbox.Tutorial #4: Using Workflow and Approvals See Also: Tutorial #4: Using Workflow and Approvals Step 7: Create a User Summary Summary Workflow rules and approval processes help you automate your business processes and enforce your standards.

However. Java™-like programming language that runs on Force. it helps to have basic knowledge of an object-oriented programming language like Java or C#. For example you can use it to write triggers.4 and the Force.php/Force.Tutorial #5: Adding Business Logic with Apex Tutorial #5: Adding Business Logic with Apex Level: Advanced. You've already added business logic using the declarative workflow environment.developerforce. This tutorial can also be completed in the Force. To do this. see Creating and Logging into a Sandbox on page 94. but it is not required. In this case. If you need help creating a project. There are two ways to develop applications on Force. Duration: 20-30 minutes Apex is a strongly-typed. Apex is used to add programmatic business logic to applications.com: you can either use the online environment. you'll create an Apex trigger that updates all open invoices whenever the merchandise price decreases. and program controllers in your app's user interface layer. Note: If you're using Free Edition. you know that it has syntax highlighting. If you have not created a sandbox yet. you will pass the savings along to your customers.com/index. code insight. In that case you'll need Eclipse 3. as you've been doing up to this point.com IDE on page 94. you will create a trigger that fires after a merchandise record is updated. In this tutorial you'll create additional logic using Apex. Software Requirements You can use the Force. Web services.3 or 3.com IDE. if you are already familiar with the IDE. object-oriented. so familiarity with Eclipse is useful but not necessary. all development must be done in your sandbox. which is ideal for juggling multiple records and complex logic.com IDE plugin: wiki. see Creating a Project in the Force.com IDE for this tutorial if you want to. Prerequisites Basic Knowledge For this tutorial. or use the Force.com. 41 . The business case you'll be working on requires that when a price for a piece of merchandise goes down. A trigger is a set of code that fires at a particular time in the lifecycle of a record.com IDE. and many other features that make development—especially team development—highly productive. If you don't have the IDE installed.com_IDE. it will take a moment to set up.

3. If you're using the Web interface. Select after update. In the Object drop-down list. On the Merchandise detail page. Click Your Name ➤ Setup ➤ Create ➤ Objects in the sidebar menu. the system won't let you save. 4. 2. 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. make sure that you have the proper permissions to create Apex classes. because if you've made syntax errors. click Quick Save. scroll down to Triggers and click New. (Ignore the warning that pops up about how you must select an operation. which will save your work and let you continue editing. 42 . Click your Merchandise custom object. and an action that fires the trigger.com IDE: 1. To create the trigger in the Force.” and “Author Apex” permissions Since this tutorial involves working with Apex. To create a trigger in the Web interface: 1. enter HandleProductPriceChange for the name.com IDE. Saving your work at this point also verifies that you've entered the code correctly.Tutorial #5: Adding Business Logic with Apex “Developer Mode. which contains the trigger name. the affected object.) 4.” “Modify All Data. In the Package Explorer. right-click your project and click New ➤ Apex Trigger. You can create triggers in the Web interface or in the Force. 3. In the dialog box. Instructions are provided for both tools. choose Merchandise__c. click Refresh Objects. 2. Replace <name> and <events> so that the code matches the following: trigger HandleProductPriceChange on Merchandise__c (after update) { } 5. Note: If this object doesn't appear in the list of object.

but it's now ready to accept any logic that you want to execute when a Merchandise record is updated.. Between the square brackets. so there are often line breaks where they aren't strictly needed. such as inserts. your Merchandise__c custom object. j. Apex ignores white spaces. that's OK.Invoice_Statement__r. Also.Price__c FROM Line_Item__c j WHERE j. so if you like to use lowercase.. List<Line_Item__c> openLineItems = [SELECT j. Apex isn't case sensitive. // update invoice line items associated with open invoices List<Line_Item__c> openLineItems = [ ]. Your trigger doesn't do anything yet.Unit_Price__c.Merchandise__r. updates and deletes—either before or after one of these events. See Also: Tutorial #5: Adding Business 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. we won't comment everything here. Note: For the sake of brevity. enter a query that pulls information from your Line Item custom object.id IN :Trigger. 43 . { }—The code that goes between the curly brackets is called the body and determines what the trigger does. so if the format of your code doesn't look exactly the same. Apex triggers are fired in response to data actions. Click Finish and the file opens in the Editor. let's break up the trigger definition and examine each part.Tutorial #5: Adding Business Logic with Apex 5. Tell Me More.Status__c = 'Negotiating' AND j. enter the following comment and then declare a list variable. 1. 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. You don't need all the line items. you can enter select instead of SELECT. 2. • • • • HandleProductPriceChange—The name of the trigger. Before we get to the trigger logic. for example.Merchandise__r. You'll code the trigger body next. on Merchandise__c—The object the trigger acts on— in this case. Note: We try to make our code samples fit on the page. but its good practice to comment your code.. (after update)—The action that fires the trigger. Between the curly braces of your trigger definition.new FOR UPDATE]. The trigger you defined fires after a record is updated.

Tutorial #5: Adding Business Logic with Apex

Tell Me More....
The openLineItems list holds a list of records from your Line_Item__c custom object. What's contained in that list is determined by the query inside the square brackets, which is written in the Salesforce Object Query Language (SOQL). Let's take a look at that query in detail. • • • • •
SELECT—Determines which fields are retrieved on the object. FROM—Determines which object or objects you want to access. 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”. WHERE—This is the start of the condition statement. In this case you want to return only those records where the status

is Negotiating. AND—This is the second condition of your statement. It pulls only the unique IDs of the records that are new. The code uses a special variable, Trigger.new, which is automatically initialized with the identifiers of the records being updated. FOR UPDATE—This tells the platform to lock the records, preventing other program or users from making updates to them. The lock remains until the trigger is complete.

See Also:
Tutorial #5: Adding Business 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, you created a list of line items and stored it in a variable called openLineItems. Now you can iterate through the list using a for loop and modify an item's original price if its new price is lower. 1. Declare a for loop.
for (Line_Item__c li: openLineItems) { }

2. Between the curly brackets, enter a conditional if statement.
for (Line_Item__c li: openLineItems) { if ( li.Merchandise__r.Price__c < li.Unit_Price__c ){ } }

3. Between the for loop's curly braces, enter code that updates the price.
for (Line_Item__c li: openLineItems) { if ( li.Merchandise__r.Price__c < li.Unit_Price__c ){ li.Unit_Price__c = li.Merchandise__r.Price__c; } }

4. The for loop is complete. Now you want to update the line items. Before the trigger's final curly brace, add the following.
update openLineItems;

44

Tutorial #5: Adding Business Logic with Apex

5. During development you typically leave a trigger inactive. To try out the trigger, you'll need to activate it. • • If you're using the Web interface, select the Is Active checkbox, which becomes available after saving the trigger. If you're using the IDE, click the Metadata tab and change the status value to Active.

6. Verify that your code looks like the following and then Save.
trigger HandleProductPriceChange on Merchandise__c (after update) { 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]; for (Line_Item__c li: openLineItems) { if ( li.Merchandise__r.Price__c < li.Unit_Price__c ){ li.Unit_Price__c = li.Merchandise__r.Price__c; } } update openLineItems; }

Tell Me More....
The final statement, update openLineItems, updates the records in the database. That's simple enough, but what about that for loop? • • •
for (Line_Item__c li: openLineItems) { }—Iterates over the list of open line item. As you iterate, the current line item is assigned to the variable li. if (li.Merchandise__r.Price__c < li.Unit_Price__c ) { }—Check to see if the price on the merchandise

record is lower than the current price. You only want to take an action if this is true. li.Unit_Price__c = li.Merchandise__r.Price__c;—Finally, update the unit price on the current line item (assigned to variable li) with the new merchandise price.

See Also:
Tutorial #5: Adding Business 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. First you need to create a new invoice statement and order at least one product, or modify an existing one. The only requirement is that you change the status field of the invoice statement to Negotiating. Then you'll

45

Tutorial #5: Adding Business Logic with Apex

lower the unit price of a merchandise item used in one of the line items of that invoice, and verify that your line item and invoice values are updated. 1. 2. 3. 4. 5. 6. 7. 8. Click the Invoice Statements tab. Click the name of an existing invoice statement. Change its Status to Negotiating and click Save. Take note of the Total Value of the invoice. Now click on a Line Item, and note its Unit Price. Click the Merchandise tab, and select the Wee Jet record (or any other item used in the line items). Edit the record, lowering the unit price. If you want an extreme reduction, change it to .01. Navigate back to the Invoice and the Line Item. Note how the values of the line item and the invoice have automatically changed.

Tell Me More....
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. However, just because a merchandise record was updated, that doesn't mean your trigger should update the record. For example, you may have updated the merchandise record's description, or increased its price, and neither of these cases requires the trigger to fire. Ideally this trigger should iterate over the Trigger.new set (the list of Merchandise records that have been updated), creating a new set of these records that pass the price criterion, and only then retrieve the related line item records.

See Also:
Tutorial #5: Adding Business Logic with Apex Step 3: Iterate Through the List and Modify Price Summary

Summary
In this tutorial, you built on the application by adding business logic that updates all open invoices when the unit price of a merchandise item goes down. To do this, you defined a trigger that executes whenever a merchandise record is saved with a lower unit price. Triggers are very useful in scenarios such as these—when you need to update multiple records on a particular condition. You can have more than one trigger associated with an object that can be triggered under different events and conditions. An important part of creating Apex triggers is making sure you have automated tests that verify that your trigger works as it should. You'll learn about testing in Tutorial #6: Adding Tests to Your Application on page 47.

See Also:
Tutorial #5: Adding Business Logic with Apex Step 4: Test the Trigger

46

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

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

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

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

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

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

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

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

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

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

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

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

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

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

For example. the functionality is there. Your page is highly configurable. Now that you have created some Visualforce components.Tutorial #7: Building a Custom User Interface Using Visualforce • Although pagination isn't shown in this example. If you have enough records to page through them. <apex:commandLink action="{!next}" value="Next" rendered="{!hasNext}" /> See Also: Tutorial #7: Building a Custom User Interface Using Visualforce Step 4: Add a Controller to the Page Summary Summary Congratulations! You have created a new interface for your Warehouse application by creating a Visualforce page that uses a standard controller. you can expose this functionality on a public website. For example. You'll find out about that in the Tutorial #8: Creating a Public Web Page Using Sites tutorial. It also provides a way of saving records. See Also: Tutorial #7: Building a Custom User Interface Using Visualforce Step 5: Display the Inventory Count Sheet as a Visualforce Page 61 . add the following code below the commandButton for page-flipping action. through its quicksave method. The page also makes use of a lot of functionality provided by the standard controller behind the scenes. the controller automatically queries the database and finds all merchandise records and assigns them to the products variable. you can easily modify which data is displayed in each row by modifying the column components.

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

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

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

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

it should be called Catalog. click Edit.force.. 7.com/Meme (depending on your domain name of course). and made it the home page for that site. Force. Scroll down to the Custom Object Permissions section and select the Read permission for the Merchandise object.. • You've assigned a single Visualforce page to the site. you will be able to access it with a URL something like http://workbook-developer-edition. Click Public Access Settings and then in the Profile Detail section. Click Save. For example. 3. 4. Note: If you still have an authorization required message.Tutorial #8: Creating a Public Web Page Using Sites page.. Tell Me More. • 66 . 5.com keeps track of the number of page views a Developer Edition site and imposes a daily bandwidth limit on the site. you probably didn't set your Active Site Home Page to Catalog in the previous step.na1. 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. This is because the anonymous website viewer hasn't yet been granted permission to view the data that the page is displaying. Let's fix this. Now go back to your website and refresh your browser and you should see your page. Go back to the setup page. Click the Site Label link. 6.

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

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

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

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

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

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

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

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

com logic.com.com includes classes that facilitate the development of Flex-based applications for Salesforce. and indicates the number of unresolved data conflicts and errors 75 . update. The framework provides: • • • • • • Seamless handling of connected and disconnected states for desktop apps.com Flex to build a basic desktop app called Inventory Tracker. Duration: 30 minutes Force. Force.com and desktop applications Generated ActionScript classes that mirror your Salesforce.com Flex Tutorial #10: Creating a Desktop App with Force.com Flex framework installs as a standalone instance of Adobe® Flash® Builder for Force.com Flex status bars. The app will provide offline access to merchandise data.com API.Tutorial #10: Creating a Desktop App with Force. which creates and manages local databases for desktop applications that operate online and offline Data synchronization between Salesforce.com Flex is a framework for creating Flex-based desktop and Web applications that leverage Salesforce. and popup notifications called toasts An engine and user interface for resolving data conflicts and errors in desktop applications The Force.com objects MXML components to simplify the implementation of user interfaces that render Salesforce. and delete Salesforce.com enterprise WSDL and provide access to Salesforce.com data via asynchronous requests to the Force. including descriptions. This tutorial demonstrates how to use Force. enabling managers to track inventory on tablet PCs while on foot in a warehouse with inconsistent Wi-Fi. and security. Inventory Tracker will include: • • • • • A login screen that prompts users for their credentials and establishes connectivity with Force. and inventory counts for each item Editable details for each item a user selects A conflict resolution interface that lets users easily resolve data conflicts that occur when values in the app violate validation rules or conflict with changes made by other users A status bar that notifies users whether the app is connected to the Internet. including the detection of Internet connectivity Adobe’s Data Management Services (DMS).com when online A list of merchandise. data. Adobe Flash Builder for Force. These applications create.com Flex Level: Advanced. prices.com—an enhanced version of Adobe's Eclipse-based integrated development environment (IDE) for developing Flex applications.com data.

com Flex Application Component Attributes Step 8: Create the Inventory Tracker Window Component Step 9: Testing the Inventory Tracker application Summary Step 1: Configure Your Salesforce. See Also: Step 1: Configure Your Salesforce.com Flex Project Step 6: Import Your Enterprise WSDL Step 7: Set the Force.com. To develop or use a Force. click Your Name ➤ Setup ➤ Manage Users ➤ Users.com Flex desktop applications leverage the Connect Offline technology in Force.com Flex desktop application.com Personal Information Step 2: Create an Offline Briefcase Configuration Step 3: Generate Your Enterprise WSDL Step 4: Install and Launch Force. In Salesforce.com Flex Step 5: Create a Force.com Flex components and classes The tutorial provides all the code you need to get your first Force. we'll use standard Adobe MXML components and ActionScript classes alongside Force.com personal information. 1. 76 .com Personal Information Force.Tutorial #10: Creating a Desktop App with Force. you must have the Offline User option selected in your Salesforce.com Flex To create the app.com.com Flex desktop app up and running.

3. 3. Enter a name for your offline briefcase configuration. so create an offline briefcase configuration that includes the Merchandise object. Select your name in the Available Members list and click Add to move it to the Assigned Members list. 1. such as Inventory Tracker App Data.com Flex 2. Select the Active checkbox. 2.com. 77 .Tutorial #10: Creating a Desktop App with Force. 4. Select the Offline User checkbox. Click New Offline Briefcase Configuration.com Flex desktop application accesses only Force. The Inventory Tracker application needs to access merchandise data. 5.com. click Your Name ➤ Setup ➤ Desktop Administration ➤ Offline Briefcase Configuration. In Salesforce.com Flex Step 2: Create an Offline Briefcase Configuration Step 2: Create an Offline Briefcase Configuration Your Force. Click Save. 4.com data specified in the offline briefcase configuration assigned to you in Salesforce. Click Edit next to your name. See Also: Tutorial #10: Creating a Desktop App with Force.

Click Add. Select Merchandise and click OK. 11..Tutorial #10: Creating a Desktop App with Force. 10. Select Merchandise Name in the Order By picklist. Click Edit in the Data Sets related list. 7.. The Offline Briefcase Configuration detail page appears. 9. 8. 78 . Click Save..com Flex 6. Click Done.

one configuration might include leads and opportunities for sales representatives. Enterprise WSDL refers to the Web Services Definition Language. You can also add and update products and schedules on opportunities..com Flex Step 4: Install and Launch Force. and Force. For now. save a local copy of your current enterprise WSDL.com Flex desktop applications and Force.com provides a robust set of functionality to support both incoming and outgoing Web services calls.com Flex development projects.. activities.com Flex Step 2: Create an Offline Briefcase Configuration Step 4: Install and Launch Force. and custom object records (including relationship groups). 3. 4. Name the file enterprise.. We will import our enterprise WSDL into our development project later to create an ActionScript class for the Merchandise object. create. Use Connect Offline to view. See Also: Tutorial #10: Creating a Desktop App with Force.force. You can create multiple briefcase configurations and associate each with different users and profiles to simultaneously suit the needs of various types of offline users. 1. 2.com Flex Step 1: Configure Your Salesforce. opportunities. contacts.com objects. Extract the contents of the zip file. which describes your Force.. automatically. Connect Offline is a client application that lets you access a subset of Force. leads. You can import your enterprise WSDL into your Force. and automatically generate ActionScript classes for every object your enterprise WSDL contains. click File ➤ Save Page As.com also.com Personal Information Step 3: Generate Your Enterprise WSDL Step 3: Generate Your Enterprise WSDL Web services are a common form of integration.com/flashbuilder.com Flex Tell Me More. while another configuration includes accounts and related opportunities for account executives. 79 .com Flex Download the Force. click Your Name ➤ Setup ➤ Develop ➤ API.com data using the same browser-based interface as the online system but without an Internet connection. See Also: Tutorial #10: Creating a Desktop App with Force.Tutorial #10: Creating a Desktop App with Force. In Salesforce. edit. Click Generate Enterprise WSDL. Force. Use the classes to access Force. In your browser..com.com Flex zip file from developer. For example.wsdl and click Save. This is typically all that's needed when integrating with another system as it fully describes all the objects and the Web service..com objects in your ActionScript code. and install it as follows: 1. Offline briefcase configurations are sets of parameters that determine the records available in Force. generates a Web service end point that allows access to the data in your application.com Connect Offline. and delete accounts.

com Flex Project Step 5: Create a Force.com Flex installs as a standalone version of Adobe Flash Builder. double-click the Adobe Flash Builder shortcut on your desktop. Force. It does not affect other installations of Eclipse that you might have on your machine. When the installation is complete. select File ➤ New Project.com Flex Project in the Flash Builder folder and click Next. Adobe's integrated development environment (IDE) based on the Eclipse platform. In Flash Builder. 2. The New Project wizard opens.com Flex Project Installing Force.com Flex creates a Force.com Flex Step 3: Generate Your Enterprise WSDL Step 5: Create a Force. Force. Double-click the installer.com Flex desktop applications projects also have ActionScript classes and MXML components that let you add user interface components with the Salesforce.com Flex project: 1. Use this type of project to create Force. To open a Force.Tutorial #10: Creating a Desktop App with Force.com Flex projects are Flex projects with additional ActionScript classes that add the following functionality to Force. See Also: Tutorial #10: Creating a Desktop App with Force. 3.com Flex project type in Adobe Flash Builder.com Flex desktop applications: • • • • • Data storage and synchronization Online and offline detection Data conflict and error resolution Status bars Toaster alerts Force. Select the Force.com Flex applications.com Flex 2.com look and feel to your both desktop and Web applications. 80 .

com Flex 3. 81 . then click Next. Figure 1: Connect to Data/Service Link 5.com Flex creates a Fiber model of your enterprise WSDL.Tutorial #10: Creating a Desktop App with Force. 6. Enter Inventory Tracker as the project name. and click Finish. Select Salesforce. 4. then click Next. select Desktop (runs in Adobe AIR). Select the Data/Services tab and click the Connect to Data/Service link. Force. Select your enterprise WSDL.

When you import your WSDL.com WSDL Renders a model of your WSDL that you can visually introspect Provides code hinting and compiler warnings in Adobe Flash Builder based on your WSDL To import your WSDL: 1.com Flex Figure 2: Fiber Model of Your Enterprise WSDL You are ready to begin coding your application.com Flex creates a Fiber model of your enterprise WSDL. Select the Data/Services tab and click the Connect to Data/Service link.com Flex Step 4: Install and Launch Force.com Flex projects let you import your Salesforce.com enterprise WSDL as a data service. Force.com Flex Step 6: Import Your Enterprise WSDL Step 6: Import Your Enterprise WSDL As with other Flex projects. then click Next. Select your enterprise WSDL. Figure 3: Connect to Data/Service Link 2. Force.Tutorial #10: Creating a Desktop App with Force. See Also: Tutorial #10: Creating a Desktop App with Force. then click Next. 3.com Flex: • • • Generates ActionScript classes for every standard and custom object in your Salesforce. Select Salesforce. Force. 82 .

In the WindowedApplication component. and handles the initial synchronization of data between Force.The application component connects the Force.Tutorial #10: Creating a Desktop App with Force.com Flex application.com Flex Application Component Attributes Every Force.com and the Force. This sets the name that appears in the title bar of the application. In the F3DesktopApplication component.INFO}" filters="{['com.adobe.0" encoding="utf-8"?> <s:WindowedApplication xmlns:fx="http://ns.com/mxml/2009" xmlns:s="library://ns. 4.com Flex Project Step 7: Set the Force.adobe. 2.com Flex Application Component Attributes Step 7: Set the Force. This attribute specifies the Force. Force.com Flex application references. Modify the attributes of the flexforforce:F3DesktopApplication element in this template as follows: 1.salesforce. Your final code should look like this.com.com Flex desktop application is contained within an F3DesktopApplication component.adobe.com Flex Figure 4: Fiber Model of Your Enterprise WSDL See Also: Tutorial #10: Creating a Desktop App with Force.com/flex/spark" xmlns:mx="library://ns. <?xml version="1. set the title attribute to Inventory Tracker.com Flex application template you can modify for your Inventory Tracker application.com Flex desktop application to Force.com" title="Inventory Tracker" showStatusBar="false"> <fx:Declarations> <s:TraceTarget includeCategory="true" includeLevel="true" includeTime="true" level="{LogEventLevel.com Flex Step 5: Create a Force.salesforce.*']}"/> <flexforforce:F3DesktopApplication id="app" statusChanged="statusChangedHandler(event)" loginComplete="loginCompleteHandler(event)" loginFailed="loginFailedHandler(event)" sessionExpired="sessionExpiredHandler(event)" 83 .com Flex projects have a default MXML file that contains a Force. Open the Main.com/flex/mx" xmlns:flexforforce="http://flexforforce. 3. set the requiredTypes attribute to Merchandise__c.com objects your Force.mxml file located in src ➤ (default package) if it is not already open.

com Flex project. the details of the record appears in the top part. The main UI for your application. See Also: Tutorial #10: Creating a Desktop App with Force. The main UI of the Inventory Tracker consists of two parts. Set the FieldContainer component width to 100% and for the ID.com logic and data in your code. Save the file. <s:Label text="Put your components here"/> 2. FieldContainer components group data and simplify the process of manipulating several fields in a single operation. enter _editFieldContainer. and a Force.com Flex Step 6: Import Your Enterprise WSDL Step 8: Create the Inventory Tracker Window Component Step 8: Create the Inventory Tracker Window Component The Inventory Tracker has two users interfaces: a login dialog and a main window containing the primary functionality. as well as Force. the text displayed in the title bar. You'll enter the application logic in the default WindowedApplication component generated when you create a Force. Remove the Label component. which is in a Spark Group component.com Flex component that renders a status bar at the bottom of the application. The lower part contains a list of merchandise records. Spark and Halo. You can click on the record details to edit them. Force. The showStatusBar attribute determines whether the application renders the standard Flash Builder status bar and is set to false to allow the application to show the Force. 1. An XML Script component in which you can enter ActionScript. a VGroup component that creates a vertical grouping of the UI elements. When you select a record in that list. and the showStatusBar attribute. <flexforforce:FieldContainer id="_editFieldContainer" width="100%"> </flexforforce:FieldContainer> 84 . A Spark states component used to determine which of the UIs is presented. Inside the VGroup component. The default MXML code includes: • A Spark WindowedApplication component that specifies the namespaces.com Flex components. A Save button below the record details lets you commit those changes to Force. add a Force. • • • Modify the default code to implement the Inventory Tracker application logic as follows.com.com Flex components simplify the process of accessing Force.com Flex application opens. The component contains a layout component used to arrange your UI elements.Tutorial #10: Creating a Desktop App with Force.com Flex status bar instead.com Flex requiredTypes="Merchandise__c"/> </fx:Declarations> 5. You don't need to modify the login UI.com Flex FieldContainer component. You'll reference the FieldContainer ID later in the code. The logic for the main functionality of the Inventory Tracker application consists of ActionScript and MXML that utilize two Adobe component sets. This component contains default ActionScript that initializes the data when the Force. The FieldContainer you're creating here will also render the details of the selected record at the top of the screen.

label it Save. mx. Leave this component as is. and configure it to execute a function called onEditSaveClick. com. and Info icon help text.com API name.DynamicEntity.salesforce.events.SessionExpiredEvent. com.events. The fields also respect field dependencies. error notification.controls.salesforce. Below the Save button in the Inventory Tracker user interface. add one Force. The code will look like this: import import import import import import import import import import import com.flexforforce.data.com Flex 3.events.salesforce. which is part of the default code.com field value with its label. A LabelAndField component renders a Salesforce.com Flex applications the same way they do on the Salesforce. mx. Begin the ActionScript by importing the classes you need for the ActionScript in the <![CDATA[ section inside the <fx:Script> element. The fields you create with the FieldAndLabel component automatically function in Force. 7.Price__c" /> field="Merchandise__c.CursorManager. but you need to add the ActionScript that retrieves Salesforce. <flexforforce:LabelAndField <flexforforce:LabelAndField <flexforforce:LabelAndField <flexforforce:LabelAndField field="Merchandise__c. Enter the code as shown below.F3Message.com user interface.Description__c" /> field="Merchandise__c. The Inventory Tracker application user interface is now in place. <mx:DataGrid id="_dataGrid" width="100%" height="100%" dataProvider="{_gridDataProvider}" itemClick="onDataGridItemClick()"> <mx:columns> <mx:DataGridColumn dataField="Name" /> <mx:DataGridColumn dataField="Description__c" headerText="Description" /> <mx:DataGridColumn dataField="Price__c" headerText="Price" /> <mx:DataGridColumn dataField="Total_Inventory__c" headerText="Total Inventory" /> </mx:columns> </mx:DataGrid> The dataProvider attribute references a variable that you'll create later.com Flex application.notifications. mx. and reference each field by its internal Force. Now add a standard Spark button.Tutorial #10: Creating a Desktop App with Force. you will display a list of merchandise records. com. which you'll write later. For example.LoginResultEvent.salesforce. <s:Button label="Save" click="onEditSaveClick()"/> 5.LogEventLevel.LoginFaultEvent.salesforce.IManaged.StatusChangedEvent.Name" /> field="Merchandise__c. The final component in the VGroup element is the Force. com. com.com Flex LabelAndField component for each field of the Merchandise object you want to display. hover details.managers.ArrayCollection. 85 . date fields display a calendar when clicked. mx. 6.logging. You'll use a standard ActionScript DataGrid component to render the list.salesforce. and automatically provide inline editing. mx.events. and the itemClick attribute references a function that you'll create later.com data and saves the data in the Force.Total_Inventory__c" /> 4.collections. Within the FieldContainer component.com Flex StatusBar component.Alert.

null) ). Create a function named onEditSaveClick that copies the changes a user makes to the data back into memory from the user interface.removeBusyCursor().}. It is used to display the selected item in the top part of the UI.Tutorial #10: Creating a Desktop App with Force. The code will use this variable to display the data in the list. app. } 86 .rpc. 9. 10. private function onEditSaveClick():void { _editFieldContainer. ArrayCollection—An ActionScript wrapper that exposes an array as a collection that can be accessed and manipulated. // when the login is complete the main state should be shown currentState = "main". Create a variable to hold the merchandise data.Merchandise__c.com Flex import mx. The classes are as follows.flexforforce. The complete function looks like this: protected function loginCompleteHandler( event : LoginResultEvent ) : void { CursorManager. [Bindable] private var _gridDataProvider:ArrayCollection = null. new mx. 8. This class is automatically generated by Force.rpc. } You referenced this function when you assigned the loginComplete attribute in the F3DesktopApplication element at the beginning of this step in the tutorial.fieldCollection.Responder. Modify this function to query the database so the merchandise data is displayed in the lower part.Responder(commitToDB.wrapper. The loginCompleteHandler() function in the default code sets the current state to main so that the main UI is displayed. Merchandise__c—The ActionScript service class representing the Merchandise object. Responder—An ActionScript component that ensures that NULL responder functions do not cause problems internally.updateObject( new mx.query( "select * from Merchandise__c". null ) ). This will be used to store the records to be displayed in the UI. • • • • • • DynamicEntity—A Force.Responder( function(rows:ArrayCollection):void {_gridDataProvider = rows. such as data conflicts.com Flex component that provides standard contextual error and information messages. import services.com Flex component that binds dynamically to any item the user selects.com Flex.rpc. IManaged—An ActionScript interface that provides the contract for a managed object. F3Message—A Force.

controls.events. private function onDataGridItemClick():void { var de:DynamicEntity = _dataGrid. 11.StatusChangedEvent. private function commitToDB(managedObject:IManaged):void { app.salesforce. and clears the data from the FieldContainer.adobe. Your final code should look like this.com" title="Inventory Tracker" showStatusBar="false"> <fx:Declarations> <s:TraceTarget includeCategory="true" includeLevel="true" includeTime="true" level="{LogEventLevel. 87 . mx.LoginFaultEvent. com. com.F3Message.flexforforce.salesforce.logging. <?xml version="1.data.events.DynamicEntity. mx.com Flex application.events.LoginResultEvent.CursorManager. _editFieldContainer. com. com.LogEventLevel. mx.render(de).wrapper. the function calls the commitToDB function.Alert.com Flex This action is triggered when the user clicks the Save button.adobe. Refer to the FieldContainer by the ID you set for it earlier (_editFieldContainer).events.selectedItem as DynamicEntity.salesforce.notifications.com/mxml/2009" xmlns:s="library://ns.adobe.*']}"/> <flexforforce:F3DesktopApplication id="app" statusChanged="statusChangedHandler(event)" loginComplete="loginCompleteHandler(event)" loginFailed="loginFailedHandler(event)" sessionExpired="sessionExpiredHandler(event)" requiredTypes="Merchandise__c"/> </fx:Declarations> <fx:Script> <![CDATA[ import import import import import import import import import import import com.salesforce.com/flex/spark" xmlns:mx="library://ns.managers.SessionExpiredEvent.fieldCollection.INFO}" filters="{['com. Save the file. which commits the data in memory to the database. Create the commitToDB function. mx.Tutorial #10: Creating a Desktop App with Force. Create a function that renders the FieldContainer data in the Force.salesforce.collections. mx. com.salesforce.salesforce.salesforce. This function also performs a simple validation of the data the user enters.save( managedObject ).com/flex/mx" xmlns:flexforforce="http://flexforforce.IManaged. If the data is valid.ArrayCollection. } 13. } 12.0" encoding="utf-8"?> <s:WindowedApplication xmlns:fx="http://ns.

rpc. // By default an alert shows that login failed. } protected function loginFailedHandler( event : LoginFaultEvent ) : void { CursorManager. CursorManager.message.rpc. [Bindable] private var _gridDataProvider:ArrayCollection = null. } protected function statusChangedHandler( event : StatusChangedEvent ) : void { status = event.preventDefault(). currentState = "login". To implement an own logic // you can prevent default by uncommenting the following line: //event.description. alertString = "Your session expired and was automatically re-newed.show( alertString.Tutorial #10: Creating a Desktop App with Force.fieldCollection.removeBusyCursor().setBusyCursor().Responder(commitToDB. event.Responder( function(rows:ArrayCollection):void {_gridDataProvider = rows. private var _username : String.selectedItem as DynamicEntity.loginByCredentials( _username. _password ).render(de). "Session Expired" ). var alertString : String. Alert.Responder. _editFieldContainer.save( managedObject ). } private function onDataGridItemClick():void { var de:DynamicEntity = _dataGrid. app.flexforforce. null) ). app.Merchandise__c.rpc. // when the login is complete the main state should be shown currentState = "main". } protected function sessionExpiredHandler( event : SessionExpiredEvent ) : void { // Alert will be shown if default is not prevented. " + "Please repeat your last operation. null ) ).query( "select * from Merchandise__c". } protected function loginCompleteHandler( event : LoginResultEvent ) : void { CursorManager. private function onEditSaveClick():void { _editFieldContainer. new mx.com Flex import mx.text. CursorManager. private var _password : String.wrapper.". 88 . import services.preventDefault(). } protected function loginClickHandler( event : MouseEvent ) : void { _username = username.setBusyCursor().}.fieldCollection.wrapper.updateObject( new mx. } private function commitToDB(managedObject:IManaged):void { app.text. _password = password.removeBusyCursor().

Name" /> <flexforforce:LabelAndField field="Merchandise__c. _password ).loginPending}" click="loginClickHandler(event)"/> </mx:FormItem> <mx:ProgressBar indeterminate="true" visible="{app.Tutorial #10: Creating a Desktop App with Force.loginByCredentials( _username.Price__c" /> <flexforforce:LabelAndField field="Merchandise__c. } ]]> </fx:Script> <s:states> <s:State name="login"/> <s:State name="main"/> </s:states> <s:VGroup includeIn="login" horizontalCenter="0" verticalCenter="0"> <s:Label text="Salesforce.loginPending}" label="{status}"/> </mx:Form> </s:VGroup> <s:Group includeIn="main" enabled="{!app.com Flex // when the login session expired the user could be re-logged in automatically pp.com Login" fontWeight="bold"/> <mx:Form> <mx:FormItem label="Username"> <s:TextInput id="username" text=""/> </mx:FormItem> <mx:FormItem label="Password" direction="horizontal"> <s:TextInput id="password" text="" displayAsPassword="true"/> <s:Button label="Login" enabled="{!app.loginPending}" width="100%" height="100%"> <s:layout> <s:BasicLayout/> </s:layout> <s:VGroup paddingTop="10" paddingLeft="10" paddingRight="10" paddingBottom="10"> <flexforforce:FieldContainer id="_editFieldContainer" width="100%"> <flexforforce:LabelAndField field="Merchandise__c.Total_Inventory__c" /> </flexforforce:FieldContainer> <s:Button label="Save" click="onEditSaveClick()" /> <mx:DataGrid id="_dataGrid" width="100%" height="100%" 89 .Description__c" /> <flexforforce:LabelAndField field="Merchandise__c.

1.com Flex dataProvider="{_gridDataProvider}" itemClick="onDataGridItemClick()"> <mx:columns> <mx:DataGridColumn dataField="Name" /> <mx:DataGridColumn dataField="Description__c" headerText="Description" /> <mx:DataGridColumn dataField="Price__c" headerText="Price" /> <mx:DataGridColumn dataField="Total_Inventory__c" headerText="Total Inventory" /> </mx:columns> </mx:DataGrid> </s:VGroup> <flexforforce:StatusBar left="0" bottom="0"/> </s:Group> </s:WindowedApplication> See Also: Tutorial #10: Creating a Desktop App with Force. In Flash Builder. right-click on the Inventory Tracker project and select Run as. ➤ Desktop Application. 90 . 2.com Flex Step 7: Set the Force..com Flex Application Component Attributes Step 9: Testing the Inventory Tracker application Step 9: Testing the Inventory Tracker application The Inventory Tracker application is now ready to be tested. Verify that your machine has an active Internet connection. The Inventory Tracker application login screen appears..Tutorial #10: Creating a Desktop App with Force.

91 . The Inventory Tracker user interface appears. enter the username and password you use to log into your Force.com Flex application. In the login screen.Tutorial #10: Creating a Desktop App with Force. and click Login.com Flex 3.

Tutorial #10: Creating a Desktop App with Force.com Flex

4. Select a record in the list and change its data, then click Save. 5. Log into your Force.com application and verify that your change appears. 6. To test the data conflict resolution capability: a. Change a field in your Force.com application and click Save. b. Change the same field in the Inventory Tracker application to a different value and click Save. c. Select the icon in the status bar and select Sync Now. When you select Sync Now in the Inventory Tracker application, the status bar icon changes to indicate a conflict exists.

7. Click Resolve in the status bar to launch the conflict resolution interface.

92

Tutorial #10: Creating a Desktop App with Force.com Flex

The conflict resolution interface lets you see the values in both Salesforce.com and the Inventory Tracker application. Select the value you want to keep, then click Continue To Summary.

See Also:
Tutorial #10: Creating a Desktop App with Force.com Flex Step 8: Create the Inventory Tracker Window Component Summary

Summary
In this tutorial, you created a simple Force.com Flex app that gives users the ability to view and edit Force.com data both with and without an Internet connection. It demonstrates the fundamentals of Force.com Flex without much coding. As you can probably imagine, you can use Force.com Flex to create far more powerful Force.com Flex apps to enhance the ways in which users interact with your Force.com apps.

See Also:
Tutorial #10: Creating a Desktop App with Force.com Flex Step 9: Testing the Inventory Tracker application

93

Creating and Logging into a Sandbox

APPENDIX
Creating and Logging into a Sandbox
If you're using Free Edition, you should do all your development in a sandbox. To create one: 1. 2. 3. 4. 5. Log into your Free Edition organization. Click Your Name ➤ Setup ➤ Data Management ➤ Sandbox. Click New Sandbox. Enter a Name, such as Dev. Click Start Copy.

Creating a copy of the production organization takes a moment. To track the progress, refresh your browser and look at the Status field. If you're not the type to watch water boil, step away and we'll email you when the copy completes. When the sandbox is available, log in: 1. If you navigated to a different page during the sandbox copy, click Your Name ➤ Setup ➤ Data Management ➤ Sandbox. 2. Next to your sandbox, click Login. 3. Your browser opens a login page, enter your password and click Login.

Tell Me More....
When you logged in, you may have noticed that the User Name field is different than your regular user name. Force.com automatically appends your sandbox name to your user name so that you can log into multiple sandboxes. You may have also noticed that the URL in your browser is different. That's because each sandbox has its own instance that's different from the one used by your regular organization.

Creating a Project in the Force.com IDE
To create a project in the Force.com IDE: 1. Select File ➤ New ➤ Force.com Project. 2. Specify your organization credentials. a. Enter a project name. You can have multiple project names on the same organization, so it helps to identify each project with a descriptive name. Call this one Workbook. b. Enter the username you use to log in as an administrator. The username is in the form of an email address. c. Enter your password. d. If you are using a sandbox for development, in the Environment field, select Sandbox from the drop-down list. e. Click Next.

94

including all of the source code. The Force.com/index. with control over the intellectual property and licensing.developerforce. From the Salesforce. you can also easily distribute upgrades to customers who installed older versions of the application. use the Force. the publisher. About Packaging Packages are like suitcases that can contain your components. 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. see “Overview of Packages” in the Force. For more information.com Migration Tool for deployment. 95 . then you'll deploy it.Delivering Your Application Note: If you get a LOGIN_MUST_USE_SECURITY_TOKEN error. code. see wiki. You must reset your security token. click Your Name ➤ Setup ➤ My Personal Information ➤ Reset My Security Token and follow the instructions there. With managed packages. If you're developing this application to be installed in multiple organizations. then you'll want to package it. the publisher.com online help. you.com platform provides two types of packages: unmanaged and managed: • Unmanaged packages are used to distribute copies of the bundled components. Delivering Your Application Now that your application is complete.php/Migration_Tool_Guide. or applications. About Deploying If you want to deploy your code to a production organization that you have login credentials for. there are a couple options available: • If you're comfortable with a command-line interface. Managed packages are used to distribute copies of the bundled components in a way that leaves you. If you're developing this application for just one organization. Once an unmanaged package is installed in another organization.com user interface. you'll want to know about the various ways you can deliver it. it means your current IP is not recognized from a trusted network range.com AppExchange. • For more information on packaging. On the Project Content page click Finish to retrieve Apex and Visualforce and components. These are typically free packages without the option to upgrade. 3.

developerforce.com/index.com IDE. use the Force.Delivering Your Application • If you prefer a graphical interface. see wiki. 96 .php/Force.com_IDE. For more information.

Sign up to vote on this title
UsefulNot useful