filemaker pro 11 the missing manual phần 9 pps

91 440 0
filemaker pro 11 the missing manual phần 9 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

704 FM P : T M M Putting a Complex Script Together Putting a Complex Script Together Building a complicated script takes time and planning. Because scripting gives you so much flexibility, you often have many ways to solve the same problem. Your job is to find the way that best meets your business needs and is the simplest to under- stand, fix and maintain later. As your skills grow, the approach you take to solving problems will change. In this section, you’ll make a script that generates an invoice for a job. You want to gather all the unbilled expenses and timeslips for the job, and then add the appropri- ate line items to the invoice. To make a script like this, you need to cover all your bases: • Planning. Before you even start writing the script, you have to decide upon a general approach. Outline all the things your script will do, and in what order. This process usually evolves from the general to the specific. The most specific version is the script itself, where you tell FileMaker exactly what to do. • Exceptions. What kinds of things can go wrong? Think about how you’ll check for errors and prevent problems. • Efficiency. Are you doing the same things several places in the script? Are there other reasons to break your script into multiple smaller scripts? Note: The rest of this chapter is one long exercise. Here, you’ll get a chance to put theoretical concepts to practical use. Since each section builds on the one before it, this complex script is best digested if you work straight through from here to the end—without skipping parts or jumping around. And while you may not need this exact process in your real life databases, the techniques you’ll learn are applicable to any complex scripting situations. Planning the Script Planning a big script is usually an iterative process. You start by outlining the steps the script will take in very general terms. You then go in and fill in more and more detail with each pass. When you’re done adding detail, you know exactly what steps your script will use. Using the invoicing script as an example, you’ll see how File- Maker gives you the tools to plan and execute your new script. You can do this planning on paper, or in a word processor, or with any other tool you choose. But one good place you may not think of is the script itself. Since the plan- ning process involves a series of steps, and since it naturally produces the finished script when it’s done, make notes with comment script steps. As you work, replace a comment line with real script steps, and perhaps more comments explaining the process. That way, you never get lost or forget essential steps because you always have a comment to tell you what you still need to add, and where it should go. When you’re done, the script is written and commented for posterity. 705  :   Putting a Complex Script Together For this script, take a look at the script shown in Figure 16-17. To save you time, it’s already created for you in the sample database for this chapter (Invoice START.fp7). Figure 16-17: This first draft of your script doesn’t do any- thing yet. It’s just a se- ries of comments that map out, at the most general level, what the script is going to do. You’ll add more and more details as you go. Since these comments are place- holders for the real steps and comments you’ll build, each one starts with the word TODO. Use any marker you want, as long as you can easily tell these placeholder comments apart from the real comments you’ll add later. Considering Exceptions One of the most critical steps in script writing—planning for exceptions—is often forgotten. But the old saw “A stitch in time saves nine” truly applies to scripting. Spend a few minutes at the beginning of the process thinking ahead to what might go wrong and planning how to prevent problems. These few minutes can save you hours of troubleshooting and repair work on your data later. Look at what your script is supposed to do and try to think of reasonable exceptions— situations where your script might not be able to do its job. Thinking of exceptions is important for two reasons: • If your script always assumes ideal circumstances, it can wreak havoc if your assumptions are wrong when it runs. The last thing you need is a wild script running amok in your data, changing and deleting the wrong things. • If a script gets halfway through its job, and then discovers that it can’t continue, you may be left with half-finished work. It’s usually best to look for the problems up front, so the script can simply refuse to run if it won’t be able to finish. (For more detail, see the box on page 707.) 706 FM P : T M M Putting a Complex Script Together For example, the Invoice creation script may run into two potential problems: • How does the script know which job to create an invoice for? This problem is easy to solve: Make the script available only through a button on the Job layout. That way, people can run the script only from the right context. In other words, the script always runs on the job record the user is looking at. Make a comment at the top of your script that reminds you how the script is run. • What if the job has no timeslips or expenses that haven’t been billed? You wind up with an invoice that has no line items, and you don’t want to send that to your customer nor do you want that laying around in your database. You can go ahead and create the invoice, and then delete it if it’s empty. But this approach uses up an invoice number, and it means your script has to go through all the work of creating an invoice only to throw it away when it’s done. Instead, have the script check first to be sure there’s something to bill. Then it can display an informative message and skip all the hard work when there’s nothing to bill. Figure 16-18 shows how to edit your script to take these two problems into account. Figure 16-18: Your first pass at edit- ing the script shows where you’ll put the test that determines whether an invoice needs to be created. And since you want to show the user a mes- sage if no invoice is made, add the Show Custom Dialog script step to the If part of the test. • The If step doesn’t need a fully realized test yet. Put a commented calculation (page 381) as your test for now, just to remind yourself what needs to be tested. You can put the real test in later. • Add feedback by putting a custom dialog step in the true part of the If step. If you don’t give feedback here, the person using the database may become con- fused, since nothing happens when he clicks the button to create an invoice for the job. The dialog box should explain why FileMaker isn’t creating an invoice. 707  :   Putting a Complex Script Together • Add an Else step. Since you don’t want to create an invoice if there aren’t any billable items for the job, put an Else step after the Show Custom Dialog step and put the remaining TODO items in the Else part of the If test. The End If step should be at the end of the script. UP TO SPEED The Problem with Problems Although detecting problems up front is usually best, it isn’t always possible. Sometimes you can’t find out about prob- lems until your script has run partway through. Most database systems handle this problem with some- thing called a transaction, a chunk of work that’s held in limbo until you tell the database to make it permanent. In a nutshell, you open a transaction, and you then can do anything you want, but your changes don’t get saved until you commit the record. If you decide you don’t want the changes after all, you can undo the transaction. FileMaker uses this transaction concept under the hood to handle record changes, but unfortunately you have no easy way to tap into the transaction system from a script. Here’s why: When you first enter a record—using the Open Re- cords/Requests script step, for instance—FileMaker begins a transaction for you. When you exit the record—Commit Records/Requests—FileMaker commits the transaction, writing all changes to the database. If you revert the record instead—Revert Record/Request—FileMaker essentially rolls back the transaction, leaving the database untouched. Just remember that each transaction is linked to a record. For example, you can’t begin a transaction, then make changes to five different customer records and eleven invoices, and then roll back all those changes—you can only roll back the last one. But if you create, edit, or delete records in portal rows while you’re still in the record, all your changes happen in one transaction. Try this exercise in the Invoices file to explore how the transaction works. Have two windows open (Choose Windows➝New Window)—one showing the Invoice lay- out and the other showing the Line Items layout. Create a new invoice record and add a few line items. Notice that FileMaker creates the new line item records when you add items to the Line Item portal on the Invoice layout. Being very careful not to commit the record (that is, don’t hit the Enter key or click anywhere outside the fields onto your lay- out), choose Records➝Revert Record. The parent invoice record disappears, and all the child line items disappear, too. You’ve just witnessed FileMaker’s version of transactions. Knowing this, you can use the Open Record/Request script step on an invoice record, and then make changes to doz- ens of line items. Then if your script detects a problem, you can revert the invoice record, and toss out all your line item changes as well. If you absolutely, positively must have control over your transactions, arrange your scripts so they do everything through relationships from one single record. Creating Subscripts Now that you’ve figured out how to solve problems your script might encounter, you’ve come to a fork in the road. You can write a script containing all the necessary steps, but it’ll be long and hard to follow. For example, the End If steps at the end of the script will be a long way from their If and Else counterparts, making it hard to figure out where they belong. The script will be easier to read if you break it up into smaller, more manageable pieces. 708 FM P : T M M Putting a Complex Script Together When you’re trying to decide whether to write one long script or several shorter ones, you might consider a few other things. If you have several small scripts, you can run any one of them individually. This method gives you the chance to try out parts of the script to see if they work properly. Also, since you can pass errors, or script results (page 684) to scripts via script parameters (page 686), using subscripts to do some jobs often saves you the trouble later on. But in the end, either approach is perfectly valid. Some people really like short, simple scripts, even if it means more of them. Others prefer to put everything controlling a single process into the same script, no matter how long the script gets. Creating subscript placeholders For this example, you’ll be creating subscripts. Use the comment steps you wrote earlier to figure out what subscripts you’ll need. Then you can create placeholders for them by putting Perform Script steps underneath the appropriate comments. Figure 16-19 shows a repeat of your script-in-progress with places for subscripts clearly identified. Each of these scripts is relatively short and easy to understand, but you’ll have five scripts in all. (See the box on page 711 for some tips for breaking up long scripts into subscripts.) Figure 16-19: Each empty Perform Script step marks a place for a subscript you’ll create later. The first subscript will find the unbilled expenses and timeslips; the second will create the new invoice record that’s related to the job; the third will loop through all the timeslips and add the necessary line items; the fourth will do the same thing for each expense. 709  :   Putting a Complex Script Together Creating skeleton subscripts Next, you’ll create all the subscripts you need—but that doesn’t mean writing them all yet. You just need to create scripts in the Manage Scripts window, and then make some placeholder comments to remind you what they should do. Start by adding a new script called Find Unbilled Activity. You can see the Find Un- billed Activity script in its planning stage form in Figure 16-20. Figure 16-20: You’ll create the Find Unbilled Activity subscript first. Since a subscript is just another script, ap- proach it like you did the “Create Invoice for Job” script: Start with a plan. You’ll come back later and implement the actual script steps. Note: Since the script you’re building actually consists of several connected scripts, you can use a folder to keep things organized. Just click the little triangle by the New button in the Manage Scripts window, choose Folder, and then give your folder a nice name like “Create Invoices.” Now you can keep the main script and all its helper scripts in a tidy package. Now create the comments for the Create Invoice Record subscript. Here are the comments to help you remember the process when it’s time to flesh this script out: • TODO: Switch to the Invoice layout. • TODO: Create a new invoice record that’s related to the current Job. • TODO: Return to the original layout. • TODO: Send script results to the parent script. 710 FM P : T M M Putting a Complex Script Together The Process Expenses and Process Timeslips scripts are almost exactly the same. The context is different, because the data is in different tables and the data each script moves is different. But the process you’ll use to find and process totals is very similar, so your comments notes can be the same for now. You’ll create the custom pieces for each script in later exercises. Create those two subscripts shown now. Here are the comments you need to write for the Process Timeslips subscript: • TODO: Check to see if there are unprocessed timeslip records. • TODO: Make an Invoice Line Item record related to the new invoice. • TODO: Loop through found records to gather total billable hours. • TODO: Set the total in the new Invoices Line Item record. Here are the comments for the Process Expenses subscript: • TODO: Check to see if there are unprocessed expense records. • TODO: Loop through found expense records. • TODO: Make an Invoice Line Item record for each expense record. These two processes are nearly the same, except they operate on different tables. To get more practice in the following section, you’ll write each script from start to fin- ish. But as you get more scripting experience, you may find that it makes sense to write one script, test it thoroughly, and then when you’re sure it’s perfect, duplicate the script and edit the steps appropriately for the second process. To recap: In this section, you just created all four Perform Script steps in the Create Invoice for Job script, and then you made four skeleton subscripts. In the real world, you could create each Perform Script step, and then start writing the subscript while you’re thinking about that specific process. You could even start with the last sub- script and work your way backwards, if that makes sense to you. The order in which you tackle the individual steps isn’t as important as finding a method that keeps you from forgetting part of a process or getting steps out of sequence. It’s also common to start out intending to write one long script, and then as it grows, realize that you’ve got a set of steps that deserves its own subscript. Select and copy the steps for the process (cut doesn’t work in the Edit Script dialog box, unfortunately), create a new script, and then paste them into the subscript. Give the subscript a descriptive name, and then save it. Back in the parent script, delete the steps you moved to the new subscript, and then add a Perform Script step to call it. See the box on page 711 to learn when a new subscript is called for. Note: Now that all your skeleton subscripts are finished, you could go back to the main script and change each empty Perform Script step to specify its proper subscript. But if you hook up each subscript as you finish it, the main script serves as a To Do list. You can tell at a glance which scripts you’ve done and which ones still need attention. 711  :   Putting a Complex Script Together UP TO SPEED The Right Way to Create Subscripts When you think about ways to break your script into smaller pieces, you should be thinking about tasks. It makes good sense to create a smaller script to do one of the tasks needed in the larger script. It doesn’t make sense to sim- ply take a long script and break it in two, so that the last step in the first script simply performs the second script. Breaking scripts up that way has all the disadvantages of multiple scripts (more windows to work in, more scripts to scroll through) and none of the advantages (neither script is particularly simple or self-contained, and neither can be run individually for testing purposes). Also, as you look for places to use subscripts, look for opportunities for reuse. In other words, look for things the script has to do more than once in two different places. It almost always makes sense to use a subscript in this situation. In almost every case, the right way to subdivide a script is to create one master script that starts and finishes the process. The “Create Invoice for Job” script does just that. It starts by finding unbilled line items, and finishes by show- ing the invoice. Along the way, it relies on other simple scripts to get the whole job done. There’s no problem with a subscript having subscripts of its own. In fact, subscripts often do. But you should structure the entire set of scripts so that the top-level script imple- ments the highest-level logic and behavior of the entire script itself. Each subscript should, in turn, do some par- ticular task from start to finish. If the task is particularly complex, then the subscript itself might implement only it’s highest level of logic, calling on more subscripts to handle parts of the task. Since you’re in the habit of naming scripts descriptively, each subscript’s name can provide nearly as much information as a comment. When you complete the “Create Invoice for Job” script, even though it’s somewhat complex, you can easily follow its structure. The script al- most reads like a book, describing exactly what it’s doing. Finishing the Subscripts You’ve created a series of subscripts that have placeholder comments to remind you what process the script will perform. Now it’s time to finish each subscript and turn them into working scripts by replacing those comments with real script steps. The Find Unbilled Activity subscript Before you leap into finishing this script, a short refresher about what you’re trying to accomplish is in order. The Find Unbilled Activity subscript is the first step in the “Create Invoice for Job” master script, which runs when a user clicks a button on the Job layout. You’ll use a script parameter to send a Job ID to the subscript, so it can find the right items. As the name says, it finds unbilled activity by searching the Timeslips and Expenses tables for items related to this job. The first TODO item inside the script is a cinch: Just use the “Go to Layout” script step to switch to the appropriate layout. Next, for the current job, you need to find expenses that don’t have a line item ID. You’ll use a combination of Enter Find [Re- store], “Set Field with the Job ID” (from your script’s parameter), and Perform Find, 712 FM P : T M M Putting a Complex Script Together to make sure you don’t get items that have already been billed. Then, the script will count the found items so it can send that value back to the main script. Finally, you’ll do the same thing for the Timeslips table. 1. In the Manage Scripts window, double-click the Find Unbilled Activity script to edit it. Add the “Go to Layout” script step to the script. If necessary, drag the “Go to Layout” step just below your first comment. Re- member, if a script step is selected, any new step you create lands just below it. 2. In the “Go to Layout” Script Step Options area’s Specify pop-up menu, click the layout popup menu, and then choose Layout to show the Specify Layout window. Choose Expenses, and then click OK. As always, context is one of the most important concepts in getting a process right. 3. Add an Enter Find Mode script step after the Go to Layout step. Turn off the Pause checkbox, and then turn on the “Specify find requests” option. The Enter Find Mode script step appears in the step list, and then the Specify Find Requests dialog box opens. 4. If any requests are showing in the list, click Delete until they’re all gone. Click the New button. The Edit Find Request window appears. 5. From the “Find records when” pop-up menu, choose Expenses, and then click the Line Item ID field. The selected field is now highlighted. 6. Click the Insert Operator button, and then choose “= match whole word (or match empty)” from the resulting menu. Click the Add button. Click OK, and then click OK again to get back to your script. Just as the menu says, an equal sign, used alone, tells FileMaker you want re- cords where the Line Item ID field matches nothing. These are all your expenses that haven’t been billed. 7. Add the Set Field script step to the script, and then turn on the “Specify target field” checkbox. Select the Expenses::Job ID field, and then click OK. The step should appear after the Enter Find Mode step. If it doesn’t, move it there now. 8. Click the Specify button to the right of “Calculated result.” In the calculation box, type "==" & Get ( ScriptParameter ). Click OK. This calculation puts the Job ID (from the script parameter) into the field, with "==" before it, telling FileMaker you want to find records that match this ID exactly. Added to the find request above, the script finds unbilled activity for the current job. 713  :   Putting a Complex Script Together 9. Add the Set Error Capture script step to the script, and then make sure its “On” option is selected. You’re about to perform a find, and you don’t want the database user to see an error message if there are no unbilled expenses. 10. Add the Perform Find script step to the script. The script step belongs below the Set Error Capture step. Make sure you don’t select Perform Find/Replace by accident. 11. Add another copy of the Set Error Capture step to the script, this time with the “Off” option selected. You can select the existing Set Error Capture step, click the duplicate button, then drag the new step into place, and then set the option to “Off.” Once the Per- form Find step is finished, you want FileMaker to stop capturing error messages. 12. Add a Set Variable script step below Set Error Capture [Off]. Name the vari- able $unbilledItems. Set its value to Get ( FoundCount ). Save the script. Remember, you want to make sure you have unbilled items for this job before you create an invoice. By grabbing this value now, and passing it to the main script later on, the main script will have the information it needs to decide whether to create an invoice. Your script should now look like the one in Figure 16-21. Figure 16-21: The Find Unbilled Activity script is half done. You’ve got helpful comments, plus the steps to find unbilled line items that should be billed to the job for which you’re creating an invoice. Refine your script further by removing the “TODO” from your first com- ment, so you can see that it’s now an explanation of what should be happening, instead of reminders of what you still need to do. [...]... increment by the amount in the current record 720 FileMaker Pro 11: The Missing Manual Putting a Complex Script Together 7 Add a “Go to Record/Request/Page” step after the Set Variable Specify Next in the pop-up menu, and then select the “Exit after last” option Now the script goes to the next record in the found set It exits the loop automatically after it performs the looped steps on the last record The rest... list to the right If you like the typing thing, then in the Network File Path box, you can enter exactly what FileMaker needs 732 FileMaker Pro 11: The Missing Manual FileMaker Network Sharing 2 From the Hosts list, select the appropriate host The shared files show in the Available Files list (If the host computer you’re looking for isn’t listed, see the next section for advice.) 3 Select the file... add the logic you need in the appropriate spots Work in a copy of your database until you get all the kinks worked out, and then use the Import button in the Manage Script dialog box to move the finished script into your original file FileMaker Pro 11: The Missing Manual Part Five: Integration and Security Chapter 17: Sharing Your Database Chapter 18: Adding Security Chapter 19: Sharing Data with Other... below the Set Field step Name the variable $totalHours, and then set its value to $totalHours + Timeslips::Duration The script will add the hours worked on each timeslip record to the value that’s already in the variable On the first record, the variable will have 0 in it, so the result of the first calculation will be the same as the duration But every time the loop runs again, the value in the variable... example, if you type mars, then you probably see only the Mars Investigations file If you find yourself opening the same files often (a pretty common thing), select a file, and then click “Add to Favorites” When you do, FileMaker adds this file to the Quick Start dialog box’s list of favorite files (see the box on page 91 ) 734 FileMaker Pro 11: The Missing Manual Sharing over the Internet Finally, on... FileMaker adds the host’s address to the Network File Path box at the bottom of the window For example, if you select a host with the address 192 .168.1.10, then FileMaker puts fmnet:/ 192 .168.1.10/ in the box 2 Add your database name to the end of the network file path (after the “/”) Since the file you want doesn’t show in the list, you have to type its name directly You’re actually creating a FileMaker. .. step after the If step Set the “Go to Record” option to First You want to make sure the loop begins with the first record in the found set so nothing gets missed 4 Add a Loop step below the “Go to Record” step You’ll also get an End Loop step Most of the rest of your script’s steps will go between the Loop and End Loop steps 722 FileMaker Pro 11: The Missing Manual Putting a Complex Script Together 5 Add... over data Just adapt these scripts to meet your needs 724 FileMaker Pro 11: The Missing Manual Putting a Complex Script Together Figure 16-27:  The finished Process Expenses script looks like this example These comments are different from the placeholder comments you created originally Here comments group the script steps into logical chunks so it’s easier to see the reason for all the layout changes... understand the process perfectly, it’s good to leave comments intact Someone else who doesn’t have your experience may take over the database some day, and your comments will serve as a tutorial Now that the subscript is done, you have to call it from the parent script You have to pass the Job ID along to the subscript, and then you’ll need to grab the subscript’s result 718 FileMaker Pro 11: The Missing Manual. .. Layout” line in the script With the Shift key held down, click the Set Variable step, and then click Duplicate FileMaker creates an exact copy of all the selected steps They all wind up below the first set 2 Move the “TODO: Find and count all unbilled timeslip records for the current job” comment above the duplicated steps This helps you keep track of where you are in the process 3 Select the “Go to Layout” . back the way they were when it started. 10. Add an Exit Script step at the end of the script. Click the Specify button, and then type $unbilledItems in the calculation box. Save and then close the. already in the variable. On the first record, the variable will have 0 in it, so the result of the first calculation will be the same as the duration. But every time the loop runs again, the value. Select and copy the steps for the process (cut doesn’t work in the Edit Script dialog box, unfortunately), create a new script, and then paste them into the subscript. Give the subscript a descriptive

Ngày đăng: 14/08/2014, 08:21

Từ khóa liên quan

Mục lục

  • Part Five: Integration and Security

    • Chapter 17. Sharing Your Database

    • Chapter 18. Adding Security

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan