12.2. Working with JScript

To cover all the features and commands of JScript would take a whole book, so in this chapter the features used in the sample code will be covered. To start off, it is a good idea to discuss creating your routines.

The order of the JScript discussion will follow the flow in which the sample application will be created, thus providing meaningful examples as the discussion progresses.

12.2.1. Working with Custom Functions

Custom functions are even more straightforward. To create a custom function that doesn't return anything requires the following syntax:

function functionname
{

}

where functionname is the name of the function you specify.

Curley brackets are used to segment pieces of code. Besides using them for functions as described previously, you will use them for loops and branching code such as if statements. You can see more about if statements in the sections following.

12.2.1.1. Try It Out: Creating a Custom Function

For the purpose of the example in this chapter, you will be creating your own function called createFullName. This routine ultimately will take values set in the first name and last name fields (called txtFirstName and txtLastName). To start, open the form you created in the last Try It Out:

  1. Choose Microsoft Script Editor from the ToolsProgramming... menu selection. The MSE will open, placing you in the script.js file, listing comments, and the following line of code:

    XDocument.DOM.setProperty("SelectionNamespaces", 'xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2004-11-17T07:09:33"'),

    The XDocument object will be displayed in the next section.

  2. Place the cursor in the bottom line of the editor.

  3. Type in the following lines of code:

    function createFullName()
    {
     XDocument.UI.Alert("Filler for now");
    }

While the names of functions and variables discussed in the next section are case sensitive, how you name them is up to you. You should land on a standard and use it throughout out your programming. Having a standard makes it easier to document and follow your own code when you have to come back and read it at a later date.

The XDocument.UI.Alert method, introduced in the last chapter, is just to help you test that the function is being called until you put more meaningful code in place.

You will be using this function as you progress through the example. When you want to use the function you just created, you type the name of the function, with its parentheses, on a line by itself, and end the line with a semicolon. So the line of code looks like this:

createFullName();

12.2.1.2. Try It Out: Calling a Custom Function

You will be using the function you just created in the AfterUpdate events of the first and last name fields.

  1. Close the script editor, saving the file.

  2. Double-click the field called txtFirstName on your InfoPath form. The Text Box Properties dialog box will open.

  3. Click the Data Validation button. As introduced in previous chapters, this dialog box enables you to create conditions for validating your data. This is also the place where you can specify script to run for various events.

  4. Click the drop-down list under the Script label. You will see the list of possible events for the txtFirstName text box, as shown in Figure 12-5.

    Figure 12.5. Figure 12-5
  5. Select the OnAfterChange event.

  6. Click the Edit button. The MSE will open, placing you between the opening and closing braces of the new event code created.

  7. In the line just above the closing brace, type the following code:

    createFullName();

    The code will then look as follows:

    function msoxd_my_txtFirstName::OnAfterChange(eventObj)
    {
    // Write code here to restore the global state.
    if (eventObj.IsUndoRedo)
         {
           // An undo or redo operation has occurred and the DOM is read-only.
           return;
         }
        // A field change has occurred and the DOM is writable.
        // Write code here to respond to the changes.
        createFullName();
    }

    The other code, created by InfoPath for you, gives the ability to trap if the redo or undo command has been given, and it enables you to program for that event. However, you don't have to worry about that at this point.

    The // denotes comments in the code. These are used for documentation and highly recommended to use. As mentioned earlier in the chapter, they will be displayed in green.

  8. Close and save the script file.

  9. Click Preview Form. The form is displayed.

  10. Type in a name in the txtFirstName field, and then press tab. The message box is displayed (see Figure 12-6).

    Figure 12.6. Figure 12-6
  11. Repeat Steps 2 through 7 for the txtLastName field on the form.

Now that you have added your custom function to the form and are successfully calling it from events on the form, it is time now to look at some meatier topics that make scripting useful for more than just displaying an alert dialog box. The first thing to talk about is the use of variables to work with the fields on the form.

12.2.2. Using Variables

Just about every programming language uses variables. There are several types of variables in JScript: reference and value variables. Whichever type of variable you use, you must declare the variable, and then assign the value, or reference. You can accomplish this using either two lines of code, or one:

var variablename
variablename = value

or

var variablename = value

12.2.2.1. Reference Variables

The first type of variable is one that points to another object. Any operation that is performed using the variable, such as assigning a value to it, will be reflected in the object that the variable references. An example of this is assigning a variable to a field on a form. When you modify the text of the variable, the value in the field on the form is modified. This is the type of variable that will be used in this example.

12.2.2.2. Value Variables

When you assign a value to a variable of this type, a copy is made of the data you have assigned to the variable. This means that when you modify the data, it does not reflect back to the original information.

Before using the variables in a Try It Out, because so much of working with variables on InfoPath forms in script involve creating references to fields on the forms, why not start right away, and learn how to accomplish this task. To learn about working with forms in script, you need to learn more about the InfoPath object model.

12.2.3. XDocument Object

When you deal with the InfoPath object model, you will be working with XML object models as well. The main object used in the example in this chapter is the XDocument object. In the code of the last Try It Out, the following line of code was mentioned:

XDocument.DOM.setProperty("SelectionNamespaces", 'xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2004-11-17T07:09:33"'),

The previous line of code, which was added automatically when you specified that you wanted to work in script with your InfoPath form, sets up your code to use the object model used for InfoPath forms. The DOM (Document Object Model) is a standard XML object that provides a number of methods and attributes that let you manipulate an XML document, in this case an InfoPath form.

To assign a reference to an InfoPath field, as mentioned in the last section, you will use a method of the DOM object called selectSingleNode and provide the XPath to the object on the form.

var firstnameField = XDocument.DOM.selectSingleNode("//my:txtFirstName");

Note that to specify the XPath you will use "//my:" and then the name of the field you want to use. This line of code enables you to work with the field on the form by manipulating the text property of the firstnameField variable.

12.2.3.1. Try It Out: Adding References to Fields on an InfoPath Form

You will be using the function you created in the last Try It Out.

  1. Position the cursor between the opening and closing curly braces of the CreateFullName function.

  2. Type in the following lines of code:

    var firstnameField =  XDocument.DOM.selectSingleNode("//my:txtFirstName");
        var lastnameField = XDocument.DOM.selectSingleNode("//my:txtLastName");
        var lastfirstwithcommaField =
                XDocument.DOM.selectSingleNode("//my:txtLastFirstWithComma");
        var fullnameField = XDocument.DOM.selectSingleNode("//my:txtFullName");

    Your editor should now look similar to the one displayed in Figure 12-7.

For the purposes of displaying all the text in the editor, the panels on each side were collapsed. You can accomplish this by clicking the pins in each panel. Then as you need them you just bring the cursor over the tab such as Document Outline. This works the same in all the Microsoft editors.

Figure 12.7. Figure 12-7

At this point, the code merely assigns a reference to the fields on the InfoPath form and is not doing much with them. The next section discusses how to manipulate the fields using the variables.

12.2.4. Performing Operations on Variables

One of the most useful purposes of variables is being able to perform operations with them. This can take the form of performing mathematical calculations in the case of numeric type variables, or performing string manipulations in the case of character data.

In the case of working with fields as specified in the last Try It Out, because you will be working with the data in the fields on the form, you will use the text property of the fields, concatenating them with the +sign. The line of code looks like this:

fullnameField.text = firstnameField.text + ' ' + lastnameField.text

This line of code concatenates the field referenced to the firstnameField variable with a space and the field referenced to the lastnameField. The space is treated as a literal value because it is between the single quotation marks.

12.2.4.1. Try It Out: Updating the txtFullName Field from Code

Using the ongoing example in this chapter, in the InfoPath form:

  1. Choose Microsoft Script Editor from ToolsProgramming....

  2. Scroll down to the line of code that reads:

    XDocument.UI.Alert("Filler for now");

  3. Type in the following line of code:

    fullnameField.text = firstnameField.text + ' ' + lastnameField.text

  4. Close and save the script file.

  5. Click Preview Form.

  6. Type in the first and last names. The Full Name is now displayed, as shown in Figure 12-8.

    Figure 12.8. Figure 12-8

For the next task, combining last and first name with a comma, you learn how to test to make sure that both are supplied before displaying the final string. However, before seeing that code, you will add the line of code to display the error. Then using conditional branching will be discussed.

12.2.4.2. Try It Out: Displaying Last Name, FirstName

To accomplish this, you will once again use the example created in this chapter.

  1. While you are in the InfoPath form, choose Microsoft Script Editor from the ToolsProgramming... menu.

  2. Move down into the createFullName function you created, just above the line of code that reads:

    fullnameField.text = firstnameField.text + ' ' + lastnameField.text

  3. Press Enter twice to add a couple of blank lines.

  4. Type in the following line of code:

    lastfirstwithcommaField.text = lastnameField.text + ', ' +
                      firstnameField.text;

    Notice that code can wrap to another line without any special symbol. This is why the semicolon is used to designate the end of the line(s) of code.

  5. Close and save the script file. You will be returned in the InfoPath designer.

  6. Click the Preview Form button.

  7. Type in the first name of your choice.

Notice the small detail that when the first name is entered and tab pressed, the Full Name with Comma field looks a little funky with a comma displayed with only the last name, as shown in Figure 12-9.

Figure 12.9. Figure 12-9

While this is a small detail, it is a great opportunity to point out how to use conditional branching in InfoPath.

12.2.5. Conditional Branching

The term conditional branching is a fancy why of saying "if this is true, perform these tasks." Conditional statements in the case of the sample in this chapter consist of the if statement. The main syntax of the if can be seen here:

if (condition)
    {
       Statements here;
    }

where the condition will be a Boolean condition of true or false. A typical condition is one that you will use in this example:

firstnameField.text.length>0

so the full initial line of the if statement is:

if ((firstnameField.text.length>0)

with the line, or lines, of code to execute following after.

Note that if you only have a single line of code following the if statement, the curly braces aren't required. The code used in the next Try It Out uses this syntax.

There are a lot of operators you can use to compare values; in the script editor if you search on the if statement, you will see all of them.

One of the issues with the line of code just displayed is that it doesn't help with the issue in the example of the comma with no last name. To truly trap for both fields would be the way to go. To accomplish this, you need to add another condition to the if statement. By doing this you will be making a complex condition, and you can do this one of two ways, by using the logical AND or OR. In JScript you will use && for AND and || for OR. In the case of the name, you want to make sure that the first name and the last name are both included so you will use the && as shown here.

if ((firstnameField.text.length>0) && (lastnameField.text.length>0))

which is added to the code just before the line that reads:

lastfirstwithcommaField.text = lastnameField.text + ', ' +
                firstnameField.text;

This way the code just mentioned is not executed unless both name fields have characters in them.

12.2.5.1. Try It Out: Adding an Conditional If Statement

We're in the home stretch now. Using the form and code you have been using:

  1. In the editor, add the following line of code:

    if ((firstnameField.text.length>0) && (lastnameField.text.length>0))

    just before the line of code that reads:

    lastfirstwithcommaField.text = lastnameField.text + ', ' +
                     firstnameField.text;

    So, the final code looks as follows, with an extra comment line thrown in:

    function createFullName()
    {
        var firstnameField =  XDocument.DOM.selectSingleNode("//my:txtFirstName");
        var lastnameField = XDocument.DOM.selectSingleNode("//my:txtLastName");
        var lastfirstwithcommaField =
                XDocument.DOM.selectSingleNode("//my:txtLastFirstWithComma");
        var fullnameField = XDocument.DOM.selectSingleNode("//my:txtFullName");
    
        // Combine the last name and first name and display them in different formats.
    
        if ((firstnameField.text.length>0) && (lastnameField.text.length>0))
    
                   lastfirstwithcommaField.text = lastnameField.text + ', ' +
                                                      firstnameField.text;
    
        fullnameField.text = firstnameField.text + ' ' + lastnameField.text
    }

  2. Save and close the form.

  3. Click Preview Form.

The form will now open and will only add the comma when both first and last names are filled in.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.98.111