Opomba:
The user interface has been simplified in Dreamweaver CC and later. As a result, you may not find some of the options described in this article in Dreamweaver CC and later. For more information, see this article.
Dreamweaver comes with a set of built‑in server behaviors that lets you easily add dynamic capabilities to a site. You can extend the Dreamweaver functionality by creating server behaviors to suit your development needs, or by obtaining server behaviors from the Dreamweaver Exchange website.
Before creating your own server behaviors, you should check the Dreamweaver Exchange website to see if another party has already created a server behavior that supplies the functionality you’d like to add to your website. Often, a third-party developer has created and tested a server behavior that will address your needs.
If you are a web developer proficient in ColdFusion, JavaScript, VBScript, or PHP, you can write your own server behaviors. The steps to create a server behavior include the following tasks:
Write one or more code blocks that perform the required action.
Specify where the code block should be inserted within the page’s HTML code.
If the server behavior requires that a value be specified for a parameter, create a dialog box that prompts the web developer applying the behavior to supply an appropriate value.
Test the server behavior before making it available to others.
Use the Server Behavior Builder to add the code block or blocks that the behavior inserts into a page.
-
Opomba:
When entering code in the Code Block box, you can only insert a single tag or code block for each named code block (for example, myBehavior_block1, myBehavior_block2, myBehavior_blockn, etc.). If you have to enter multiple tags or code blocks, create an individual code block for each one. You can also copy and paste code from other pages.
-
After you specify the source code and insert location for each code block, the server behavior is completely defined. In most cases, you don’t need to specify any additional information.
If you are an advanced user, you can set any of the following options:
Identifier
Specifies whether the code block should be treated as an identifier.
By default, every code block is an identifier. If Dreamweaver finds an identifier code block anywhere in a document, it lists the behavior in the Server Behaviors panel. Use the Identifier option to specify whether the code block should be treated as an identifier.
At least one of the server behavior’s code blocks must be an identifier. A code block should not be an identifier if one of the following conditions applies: the same code block is used by some other server behavior; or the code block is so simple that it might occur naturally on the page.
Server Behavior Title
Specifies the title of the behavior in the Server Behaviors panel.
When the page designer clicks the Plus (+) button on the Server Behaviors panel, the new server behavior’s title will appear in the pop‑up menu. When a designer applies an instance of a server behavior to a document, the behavior appears in the list of applied behaviors in the Server Behaviors panel. Use the Server Behavior Title box to specify the contents of the Plus (+) pop‑up menu and the list of applied behaviors.
The initial value in the box is the name you supplied in the New Server Behavior dialog box. As parameters are defined, the name is automatically updated so that the parameters appear inside parentheses after the server behavior name.
Set Session Variable (@@Name@@, @@Value@@)
If the user accepts the default value, everything before the parentheses appears in the Plus (+) pop‑up menu (for example, Set Session Variable). The name plus the parameters will appear in the list of applied behaviors—for example, Set Session Variable ("abcd", "5").
Code Block to Select
Specifies what code block is selected when the user selects the behavior in the Server Behaviors panel.
When you apply a server behavior, one of the code blocks within the behavior is designated the “code block to select.” If you apply the server behavior and then select the behavior in the Server Behaviors panel, the designated block is selected in the Document window. By default, Dreamweaver selects the first code block that is not above the html tag. If all the code blocks are above the html tag, then the first one is selected. Advanced users can specify which code block is the selected one.
The code blocks you create in the Server Behavior Builder are encapsulated in a server behavior that appears in the Server Behaviors panel. The code can be any valid run-time code for the specified server model. For example, if you choose ColdFusion as the document type for your custom server behavior, the code you write must be valid ColdFusion code that runs on a ColdFusion application server.
You can create the code blocks either directly in the Server Behavior Builder, or you can copy and paste the code from other sources. Each code block you create in the Server Behavior Builder must be a single tag or script block. If you must insert multiple tag blocks, split them into separate code blocks.
Dreamweaver lets you develop code blocks that incorporate control statements that execute conditionally. The Server Behavior Builder uses if, elseif, and else statements, and may also contain server behavior parameters. This enables you to insert alternate text blocks based on the values of OR relationships among server behavior parameters.
The following example shows the if, elseif, and else statements. The square brackets ([ ]) denote optional code and the asterisk (*) denotes zero or more instances. To execute a portion of a code block or the entire code block only if a certain condition or conditions apply, use the following syntax:
<@ if (expression1) @> conditional text1[<@ elseif (expression2) @> conditional text2]*[<@ else @> conditional text3]<@ endif @>
Condition expressions can be any JavaScript expression that can be evaluated using the JavaScript eval() function, and may include a server behavior parameter marked by @@’s. (The @@’s distinguish the parameter from JavaScript variables and keywords.)
When using if, else, and elseif directives within the insertText XML tag, the participant text is preprocessed to resolve the if directives and to determine which text to include in the result. The if and elseif directives take the expression as an argument. The condition expression is the same as that for JavaScript condition expressions, and can also contain server behavior parameters. Directives such as this allow you to choose between alternative code blocks based on the values of, or relationships between, server behavior parameters.
For example, the following JSP code comes from a Dreamweaver server behavior that uses a conditional code block:
@@rsName@@.close(); <@ if (@@callableName@@ != '') @> @@callableName@@.execute(); @@rsName@@ = @@callableName@@.getResultSet();<@ else @> @@rsName@@ = Statement@@rsName@@.executeQuery(); <@ endif @> @@rsName@@_hasData = @@rsName@@.next();
The conditional code block starts with <@ if (@@callableName@@ != '') @> and ends with <@ endif @>. According to the code, if the user enters a value for the @@callableName@@ parameter in the server behavior's Parameter dialog box—in other words, if the @@callableName@@ parameter value is not null, or (@@callableName@@ != '')—then the conditional code block is replaced with the following statements:
@@callableName@@.execute(); @@rsName@@ = @@callableName@@.getResultSet();
@@rsName@@ = Statement@@rsName@@.executeQuery();
When you create code blocks using the Server Behavior Builder, you must specify where to insert them in the page’s HTML code.
For example, if you insert a code block above the opening <html> tag, you must then specify the code block’s position relative to other tags, scripts, and server behaviors in that section of the page’s HTML code. Typical examples include positioning a behavior either before or after any recordset queries that might also exist in the page code above the opening <html> tag.
When you select a positioning option from the Insert Code pop‑up menu, the options available in the Relative Position pop‑up menu change to provide relevant options for that part of the page. For example, if you select Above The <html> Tag In The Insert Code pop‑up menu, the positioning options available in the Relative Position pop‑up menu reflect choices relevant for that part of the page.
The following table shows the code block insert options, and the relative positioning options available for each:
Insert Code options |
Relative position options |
---|---|
Above the <html> Tag |
|
Below the </html> Tag |
|
Relative to a Specific Tag |
Select a tag from the Tag pop‑up menu, and then choose from the tag positioning options. |
Relative to the Selection |
Before the selection After the selection Replace the selection Wrap the selection |
To specify a custom position, you must assign a weight to the code block. Use the Custom Position option when you need to insert more than one code block in a particular order. For example, to insert an ordered series of three code blocks after the code blocks that open recordsets, you would enter a weight of 60 for the first block, 65 for the second, and 70 for the third.
By default, Dreamweaver assigns a weight of 50 to all recordset-opening code blocks inserted above the <html> tag. If the weight of two or more blocks match, Dreamweaver randomly sets the order among the blocks.
-
Specify a location relative to the selection by choosing an option in the Relative Position pop‑up menu.
You can insert your code block just before or just after the selection. You can also replace the selection with your code block, or you can wrap the code block around the selection.
To wrap the code block around a selection, the selection must consist of an opening and closing tag with nothing in between, as follows:
<CFIF Day=”Monday”></CFIF>
To repeat a portion of a code block or the entire code block a number of times, use the following syntax:
<@ loop (@@param1@@,@@param2@@) @> code block<@ endloop @>
When creating server behaviors, you can use looping constructs to repeat a code block a specified number of times. <@ loop (@@param1@@,@@param2@@,@@param3@@,@@param_n@@) @> code block <@ endloop @>The loop directive accepts a comma-separated list of parameter arrays as arguments. In this case, parameter array arguments allow a user to supply multiple values for a single parameter. The repeating text is duplicated n times, where n is the length of the parameter array arguments. If more than one parameter array argument is specified, all the arrays must have the same length. On the ith evaluation of the loop, the ith elements of the parameter arrays replace the associated parameter instances in the code block.
When you create a dialog box for the server behavior, you can add a control to the dialog box that lets the page designer create parameter arrays. Dreamweaver includes a simple array control that you can use to create dialog boxes. This control, called Text Field Comma Separated List, is available through the Server Behavior Builder. To create user interface elements of greater complexity, see the API documentation to create a dialog box with a control to create arrays (a grid control, for example).
You can nest any number of conditionals or a loop directive within a conditional directive. For example, you can specify that if an expression is true to execute a loop.
The following example shows how such repeating code blocks can be used to create server behaviors (the example is a ColdFusion behavior used to access a stored procedure):
<@ loop (@@param1@@,@@param2@@,@@param3@@,@@param_n@@) @> code block <@ endloop @>
<CFSTOREDPROC procedure="AddNewBook" datasource=#MM_connection_DSN# username=#MM_connection_USERNAME# password=#MM_connection_PASSWORD#> <CFPROCPARAM type="IN" dbvarname="@CategoryId" value="#Form.CategoryID#" cfsqltype="CF_SQL_INTEGER"> <CFPROCPARAM type="IN" dbvarname="@ISBN" value="#Form.ISBN#" cfsqltype="CF_SQL_VARCHAR"> </CFSTOREDPROC>
In this example, the CFSTOREDPROC tag can include zero or more CFPROCPARAM tags. However, without support for the loop directive, there is no way to include the CFPROCPARAM tags within the inserted CFSTOREDPROC tag. If this were to be created as a server behavior without the use of the loop directive, you would need to divide this example into two participants: a main CFSTOREDPROC tag, and a CFPROCPARAM tag whose participant type is multiple.
Using the loop directive, you can write the same procedure as follows:
<CFSTOREDPROC procedure="@@procedure@@" datasource=#MM_@@conn@@_DSN# username=#MM_@@conn@@_USERNAME# password=#MM_@@conn@@_PASSWORD#> <@ loop (@@paramName@@,@@value@@,@@type@@) @> <CFPROCPARAM type="IN" dbvarname="@@paramName@@" value="@@value@@" cfsqltype="@@type@@"> <@ endloop @> </CFSTOREDPROC>
Opomba:
New lines after each “@>” are ignored.
procedure = "proc1" conn = "connection1" paramName = ["@CategoryId", "@Year", "@ISBN"] value = ["#Form.CategoryId#", "#Form.Year#", "#Form.ISBN#"] type = ["CF_SQL_INTEGER", "CF_SQL_INTEGER", "CF_SQL_VARCHAR"]
<CFSTOREDPROC procedure="proc1" datasource=#MM_connection1_DSN# username=#MM_connection1_USERNAME# password=#MM_connection1_PASSWORD#> <CFPROCPARAM type="IN" dbvarname="@CategoryId" value="#Form.CategoryId#" cfsqltype="CF_SQL_INTEGER"> <CFPROCPARAM type="IN" dbvarname="@Year" value="#Form.Year#" cfsqltype="CF_SQL_INTEGER"> <CFPROCPARAM type="IN" dbvarname="@ISBN" value="#Form.ISBN#" cfsqltype="CF_SQL_VARCHAR"> </CFSTOREDPROC>
Opomba:
Parameter arrays cannot be used outside of a loop except as part of a conditional directive expression.
The loop directive includes two built‑in variables that you can use for embedded if conditions. The variables are: _length and _index. The _length variable evaluates to the length of the arrays processed by the loop directive, while the _index variable evaluates to the current index of the loop directive. To ensure that the variables are only recognized as directives, and not as actual parameters to be passed into the loop, do not enclose either variable in @@s.
An example of using built‑in variables is to apply them to the import attribute of the page directive. The import attribute requires comma separation of packages. If the loop directive extends around the entire import attribute, you would only output the attribute name import= on the first iteration of the loop—this includes the closing double quote (")—and not output a comma on the last iteration of the loop. Using the built‑in variable, you can express this as follows:
<@loop (@@Import@@)@> <@ if(_index == 0)@>import=" <@endif@>@@Import@@<@if (_index == _length-1)@>"<@else@>, <@ endif @> <@endloop@>
Server behaviors often require that the page designer supply a parameter value. This value must be inserted before the server behavior’s code is inserted into the page.
You create the dialog box by defining the designer-supplied parameters in the code. Then you generate a dialog box for the server behavior, which prompts the page designer for a parameter value.
Opomba:
A parameter is added to your code block without your intervention if you specify that your code should be inserted relative to a specific tag chosen by the page designer (that is, you chose Relative to a Specific Tag in the Insert Code pop‑up menu). The parameter adds a tag menu to the behavior’s dialog box to let the page designer select a tag.
-
<% Session(“lang_pref”) = Request.Form(“@@formParam@@”); %>
<% Session(“lang_pref”) = Request.Form(“Form_Object_Name”); %>
To require the page designer to supply the value of Form_Object_Name, enclose the string in parameter markers (@@):<% Session(“lang_pref”) = Request.Form(“@@Form_Object_Name@@”); %>
<% Session(“lang_pref”) = Request.Form(“@@Form_Object_Name@@”); %>
You can also highlight the string and click the Insert Parameter In Code Block button. Enter a parameter name and click OK. Dreamweaver replaces every instance of the highlighted string with the specified parameter name enclosed in parameter markers.
Dreamweaver uses the strings that you enclose in parameter markers to label the controls in the dialog box it generates (see the following procedure). In the previous example, Dreamweaver creates a dialog box with the following label:
Opomba:
Parameter names in the server behavior code cannot have any spaces. Therefore, the dialog box labels cannot have any spaces. If you want to include spaces in the label, you can edit the generated HTML file.
You can edit any server behavior created with the Server Behavior Builder, including server behaviors you download from the Dreamweaver Exchange website, and other third‑party developers.
If you apply a server behavior to a page and then edit the behavior in Dreamweaver, instances of the old behavior no longer appear in the Server Behaviors panel. The Server Behaviors panel searches the page for code that matches the code of known server behaviors. If the code of a server behavior changes, the panel does not recognize earlier versions of the behavior on that page.
In general, your server behavior’s code should be compact and robust. Web application developers are very sensitive to the code added to their pages. Follow generally accepted coding practices for the document type’s language (ColdFusion, JavaScript, VBScript, or PHP). When writing comments, consider the different technical audiences that might need to understand the code, such as web and interaction designers, or other web application developers. Include comments that accurately describe the purpose of the code, and any special instructions for including it within a page.
Keep in mind the following coding guidelines when you create server behaviors:
Error checking
An important requirement. The server behavior’s code should handle error cases gracefully. Try to foresee every possibility. For example, what if a parameter request fails? What if no records are returned from a query?
Unique names
Help to ensure that your code is clearly identifiable and avoids name collisions with existing code. For example, if the page contains a function called hideLayer() and a global variable called ERROR_STRING, and your server behavior inserts code that uses those names too, the server behavior may conflict with the existing code.
Code prefixes
Allow you to identify your own run-time functions and global variables in a page. One convention is to use your initials. Never use the MM_ prefix, as it is reserved for Dreamweaver use only. Dreamweaver precedes all functions and global variables with the prefix MM_ to prevent them from conflicting with any code that you write.
var MM_ERROR_STRING = "..."; function MM_hideLayer() {
Avoid similar code blocks
so that the code you write doesn’t resemble too closely the code in other blocks. If a code block looks too much like another code block on the page, the Server Behaviors panel might mistakenly identify the first code block as an instance of the second code block (or conversely). A simple solution is to add a comment to a code block to make it more unique.
The Dreamweaver Exchange recommends performing the following tests on each server behavior you create:
Apply the behavior from the Server Behaviors panel. If it has a dialog box, enter valid data in each field and click OK. Verify that no error occurs when the behavior is applied. Verify that the run-time code for the server behavior appears in the Code inspector.
Apply the server behavior again and enter invalid data in each field of the dialog box. Try leaving the field blank, using large or negative numbers, using invalid characters (such as /, ?, :, *, and so on), and using letters in numeric fields. You can write form validation routines to handle invalid data (validation routines involve hand-coding, which is beyond the scope of this book).
After successfully applying your server behavior to the page, verify the following:
Check the Server Behaviors panel to make sure the name of the server behavior appears in the list of behaviors added to the page.
If applicable, verify that server-side script icons show up on the page. The generic server-side script icons are gold shields. To see the icons, enable Invisible Elements (View > Visual Aids > Invisible Elements).
In Code view (View > Code), verify that no invalid code is generated.
In addition, if your server behavior inserts code in the document establishing a connection to a database, create a test database to test the code inserted in the document. Verify the connection by defining queries that produce different sets of data, and different sizes of data sets.
Finally, upload the page to the server and open it in a browser. View the page’s HTML source code and verify that no invalid HTML has been generated by the server-side scripts.