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

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

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

visit Developer Force at developer. You can find the latest version of this Workbook and additional tutorials that extend the app at developer.About the Force.. there's a lot of useful information here and some additional steps to flesh out your app.com.force. move on to the next step. • • To learn more about Force.force. if you're a smell-the-roses type. 4 . However.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..com and to access a rich set of resources. If you like to do things quickly.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.com Flex Appendix Creating and Logging into a Sandbox Creating a Project in the Force.com/workbook. At the end of each step there is an optional Tell Me More section..

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Merchandise__r. If ISNEW is true. Merchandise__r. An invoice could be made up of multiple line items. 5. then you simply check inventory as you did previously. you return FALSE to indicate that there's no validation failure.. 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. then you've updated the record and decreased its units. Click Save. not creating a new record. If ISNEW is false.. If the prior value was greater.. Replace the existing formula with the following. Let's look at this formula in a little more detail. 3. by comparing it to its prior value using the PRIORVALUE function. 2. This function returns true if you're creating a new record.Tutorial #3: Using Formulas and Validation Rules 1. IF ( Units_Sold__c < PRIORVALUE(Units_Sold__c).PRIORVALUE(Units_Sold__c)) ) ) 4. 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.Total_Inventory__c < Units_Sold__c . FALSE. false otherwise. For new records.Total_Inventory__c < (Units_Sold__c . this time to determine if the number of units has gone up or down. Scroll down to the Validation Rules related list. Since you have enough stock. IF( ISNEW(). Click Check Syntax to make sure there are no errors. you need to check that you have • • not sold more than you have in stock. 26 . ISNEW is the condition. • • • • IF is a conditional. ensuring that at run time one of the two branches will be taken depending on the condition. If the prior value was smaller. you know that you're performing an update to an existing 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. so you created a roll-up summary field to automatically add up the line item subtotals. Tell Me More. so you perform another conditional check. so you have to check whether there's enough inventory to hold the difference between the new number of units and the old.

The first version of the rule was simple. and existing records with updates. but you enhanced it to work with both new records. These kinds of modifications can be applied to any field in your app when you want to make sure the data entered meets certain criteria. See Also: Tutorial #3: Using Formulas and Validation Rules Step 5: Improve the Validation Rule 27 .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.

criteria. 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. You can create this complex logic quite easily with a declarative workflow rule. field updates. The first carries the current price of a merchandise item into the newly created line item record. Approval processes can automate all of your organization's approvals—from simple to complex. you've created the Line Item and the Merchandise objects with Price fields.com app. you can use workflow rules and approval processes to automate your procedures and processes. 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. and the second updates the inventory whenever you update a product line item. Not only do they save time. though you probably didn't notice that in the user interface because your default user is an administrative user. and formulas. Workflow rules can trigger actions (such as email alerts. 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. In your Force. In this tutorial. who has access to all data. they also enforce consistency and compliance within your company's business practices. You've also marked the Line Item Price field as read-only. 28 .Tutorial #4: Using Workflow and Approvals Tutorial #4: Using Workflow and Approvals Level: Intermediate. you create and test two workflow rules. 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. tasks. You will also create an approval process that requires explicit approval from the manager if an invoice is over $2000.

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

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

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

3. Click Save. 19. click the lookup icon and select the Wee Jet merchandise record. Set Units Sold to 1000. 2. 32 . Click Save to close the New Field Update wizard and return to Step 3 of the Workflow wizard. Note that the unit price has been set to the same value as on the Wee Jet record. click Activate. Leave the Unit Price field blank. Next to the Merchandise field. 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. Then verify that its unit price is automatically set and that the total inventory on the stock has decreased. On the Workflow Rule page. 1. 18. 4. Click line item 2. 5. On the Specify Workflow Actions page.Tutorial #4: Using Workflow and Approvals 17. click Done. Click the Invoice Statements tab. • • • • In the Line Item Number field enter 2. Click the invoice record you created earlier. Select New Line Item and enter the following values.

Verify that your screen looks like the following. 6. enter Large Invoice Template. 2.LastModifiedDate} 8.Invoice_Value__c} on {!Invoice_Statement__c. select Text and click Next. Select Available For Use. just assume we're talking about whatever currency you're using. 7. enter A large invoice has been submitted. You create the approval process in the next steps. and an approval process for the manager to follow. 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. 1. {!Invoice_Statement__c. In the Subject field. 3. Click New Template. Note: If your default currency is not set to US dollars. 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. In the Email Template Name field. To implement this rule you need to create two additional elements: an email to be sent to the manager when an invoice exceeds $2000. Click Your Name ➤ Setup ➤ Communication Templates ➤ Email Templates. 5.Tutorial #4: Using Workflow and Approvals 6. and then click Save. Notice that the Total Inventory is down to 1000 from 2000 (or whatever you entered). In Step 1 of the Email Template wizard. In the Email Body field. 4. enter the following code and text.OwnerFullName} submitted for approval an Invoice Statement that totalled {!Invoice_Statement__c. 33 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

and the test case you have just written misses one. Right now it only checks invoice statements that have a status of Negotiating. then raising or lowering the price shouldn't have any effect.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. But it's important to note that code coverage isn't the only goal for testing. 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 . if an invoice statement does not have a status of Negotiating. It should also check other status values. Creating unit tests as you develop is necessary for deployment and it's also the key to successful long-term development. For example.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Select your enterprise WSDL.com enterprise WSDL as a data service.com Flex: • • • Generates ActionScript classes for every standard and custom object in your Salesforce.com Flex creates a Fiber model of your enterprise WSDL. See Also: Tutorial #10: Creating a Desktop App with Force.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 Step 6: Import Your Enterprise WSDL Step 6: Import Your Enterprise WSDL As with other Flex projects. Force. Figure 3: Connect to Data/Service Link 2. 3.com Flex projects let you import your Salesforce.Tutorial #10: Creating a Desktop App with Force.com Flex Figure 2: Fiber Model of Your Enterprise WSDL You are ready to begin coding your application. When you import your WSDL. 82 . Force. Select Salesforce. then click Next.com Flex Step 4: Install and Launch Force. Force. Select the Data/Services tab and click the Connect to Data/Service link. then click Next.

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

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

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

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

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

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

Tutorial #10: Creating a Desktop App with Force.loginByCredentials( _username.loginPending}" click="loginClickHandler(event)"/> </mx:FormItem> <mx:ProgressBar indeterminate="true" visible="{app.Description__c" /> <flexforforce:LabelAndField field="Merchandise__c.Name" /> <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 . } ]]> </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}" 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.com Flex // when the login session expired the user could be re-logged in automatically pp.Price__c" /> <flexforforce:LabelAndField field="Merchandise__c.loginPending}" label="{status}"/> </mx:Form> </s:VGroup> <s:Group includeIn="main" enabled="{!app.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. _password ).

. ➤ Desktop Application..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. right-click on the Inventory Tracker project and select Run as. The Inventory Tracker application login screen appears. 1. In Flash Builder.Tutorial #10: Creating a Desktop App with Force. 2. Verify that your machine has an active Internet connection. 90 .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.com Flex Step 7: Set the Force.

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

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

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

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