1. Trang chủ
  2. » Công Nghệ Thông Tin

The Essential Guide to Dreamweaver CS4 with CSS, Ajax, and PHP phần 10 pptx

94 309 0

Đ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

Thông tin cơ bản

Tiêu đề The Essential Guide To Dreamweaver Cs4 With Css, Ajax, And Php
Trường học Standard University
Chuyên ngành Web Development
Thể loại Hướng dẫn
Năm xuất bản 2009
Thành phố New York
Định dạng
Số trang 94
Dung lượng 3,47 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

So, let’s create the table and generate the HTML source for theSpry data sets that will be used for the gallery.. pho-The HTML data source that will be used for the Spry data sets will d

Trang 1

Generating the HTML source

You can use any HTML structure to populate a Spry data set, as long as it presents data in

a predictable manner An existing table or list created in a static web page will do, but it’sfar more efficient to use a recordset Not only is the data in an organized structure, butalso the HTML structure is automatically updated whenever changes are made to the data-base table To speed things up, I have created a SQL file to create the ch19_gallery tableand populate it with data So, let’s create the table and generate the HTML source for theSpry data sets that will be used for the gallery

The following instructions show you how to load the ch19_gallery table into the dwcs4database:

1.Load phpMyAdmin into your browser, and select the dwcs4 database

2.Select the Importtab, and click the Browsebutton to navigate to ch19_gallery.sql

in the extras folder of the download files for this book If you’re using MySQL 4.0,choose ch19_gallery40.sql instead

3.Click Goto import the SQL, which will create the ch19_gallery table and populate

it with data

4.Select the ch19_gallery table in the navigation frame on the left side ofphpMyAdmin The first few records should look like Figure 19-2

Figure 19-2 The ch19_gallery table contains details of photos of England and Japan.

Each record contains the file name, dimensions, caption, and description of a tograph, plus the category to which it belongs: JPN for Japan and ENG for England

pho-The HTML data source that will be used for the Spry data sets will display the galleryimages and thumbnails in plain tables This exercise shows you how to bind the file namesand dimensions of the images to <img> tags through the Bindingspanel

1.In Dreamweaver, create a new PHP page, and save it as gallery_eng.php in

Generating the HTML tables Creating the database table

Trang 2

2.Open the Recordset dialog box in Simple mode Name the first recordset

getENGphotos, use connQuery as the connection, and select the ch19_gallery table

3.In the Columnsfield, select the Selectedradio button, hold down the Ctrl/Cmd key,

and select all the columns except photo_id and category

4.You want the recordset to contain only those records that belong to the ENG

cate-gory, so select category from the Filter drop-down menu Leave the drop-down

menu alongside on the default equal sign Then select Entered Valuefrom the left

drop-down menu in the next row This lets you specify the desired value in the field

alongside So, type ENGin that field The values entered in the Recordset dialog

box should look like this:

5.Insert a table with two rows and four columns Make the table 100-percent wide,

and insert table headers in the first row like this:

19

6.The recordset contains the file names of photos in the images/gallery folder

Smaller thumbnail images have the same names as their larger equivalents and are

stored in images/gallery/thumbs To display the images, you need to bind the

data in the recordsets to <img> tags This is done through a combination of the

Select Image Sourcedialog box and the Bindingspanel

Position your cursor inside the first cell of the second row, and click the Imagebutton

on the Insertbar Alternatively, select Insert➤Image, or press Ctrl+Alt+I/Opt+Cmd+I

Trang 3

7.In the Select Image Source dialog box, navigate to the images/gallery/thumbsfolder, select the value in the URLfield, and cut it to your clipboard Then selectthe Data sourcesradio button at the top of the dialog box, as shown in the follow-ing illustration (In the Mac version of Dreamweaver, Data sourcesis a regular but-ton located at the bottom of the dialog box.)

8.When you select Data sources, the Select Image Source dialog box displays therecordsets and any other dynamic data sources available to the page Expand thegetENGphotosrecordset, and select filename This inserts the necessary PHP code inthe URLfield However, you need to add the path to the thumbs folder, so positionyour cursor in front of the PHP code, and paste the value from your clipboard, asshown in the following illustration Then click OK(Chooseon a Mac) to close thedialog box

Trang 4

9.In the Image Tag Accessibility Attributesdialog box, activate the Alternate text

drop-down menu to select <empty>, and click OK

10.You now have a dynamic image placeholder in the first cell of the table With the

placeholder still selected, enter 80in the field labeled Wand 54in the field labeled

Hin the Property inspector This sets the width and height of the image All the

thumbnails are the same size, so you can insert explicit values

11.Next, you need to create dynamic placeholders for the main images Since the

main images and thumbnails use the same file names, repeat steps 6–9, only this

time your cursor should be in the second cell, and in step 7, navigate to the

images/gallery folder

12.The main images are different sizes, so you need to bind the width and height from

the recordset You can also use the caption as the alternate text

To do this, open the Bindingspanel, and expand Recordset (getENGphotos) With

the dynamic image placeholder still selected in the second cell, select widthfrom

the getENGphotos recordset Then activate the Bind todrop-down menu at the

bot-tom of the Bindingspanel, select img.width, and click the Bindbutton, as shown in

Figure 19-3 This inserts PHP code in the image’s width attribute so that it uses the

correct value from the recordset

13.Repeat step 12, binding heightfrom the recordset to img.height, and caption to

img.alt

14.Insert dynamic text placeholders for the caption and description columns in the

third and fourth cells Your page should now look like this:

Figure 19-3.

Use the Bindings panel toapply dynamic values toattributes of the selected tag

19

Trang 5

15.Save gallery_eng.php, and click the Live Viewbutton to check that the data isbeing displayed correctly, as shown in Figure 19-4.

Figure 19-4 The raw data is contained in an unstyled table.

16.If everything is OK, deactivate Live view, click inside the second row of the table,and select <tr>in the Tag selector at the bottom of the Document window Apply aRepeat Region server behavior to display all records

17.Select the whole table, and give it an ID by typing ENGdatainto the field on the leftside of the Property inspector

18.Save gallery_eng.php, and test it in a browser You should see a table with eightrecords displaying similar content to that shown in Figure 19-4

19.Create another page called gallery_jpn.php It should be identical togallery_eng.php, except it should display the Japanese photos In step 4, call therecordset getJPNphotos, and enter JPN in the field alongside Entered Value Instep 17, use JPNdataas the ID for the table

20.Check your code, if necessary, against gallery_eng.php and gallery_jpn.php inexamples/ch19

Now that your data is in a predictable structure, you can use the Spry Data Set wizard

Using the Spry Data Set wizard

The way you create a Spry data set has been completely rethought in Dreamweaver CS4.The Spry XML Data Setand Spry Tablebuttons and menu commands have been replaced

by a single option, Spry Data Set, which launches a wizard that takes you through theprocess of creating the data set in a visual and intuitive manner It also creates the basic

Trang 6

To use the Spry Data Set wizard, the data source must be in one of the following formats:

HTML table: The table must have an ID Data can be stored in either rows or

columns The wizard regards each table as a data container.

HTML elements: The wizard can extract data stored in any HTML elements The

parent element (or data container) must have an ID, and the category or column

that each child element belongs to needs to be clearly identifiable This is usually

done by assigning a class For example, instead of building the tables in

gallery_eng.php and gallery_jpn.php, you could put the same information

in paragraphs and identify the thumbnails, images, captions, and descriptions

with class names This is probably the most cumbersome way of creating a data

container

XML: You can use a static XML document or one generated dynamically from a

database

The wizard takes you through three steps, as follows:

1.Selection of the data source

2.Data configuration

3.HTML layout

You can omit the final step if you don’t want Dreamweaver to create HTML to display the

data set The first two steps are identical for every data set The final step offers a number

of different options Let’s start by walking through the wizard to create a Spry data set and

display it in a table

Displaying a data set in a Spry table

The final step of the Spry Data Set wizard has options for setting classes on alternate rows

of a Spry table So, before diving into creating a Spry table, you need to do a little planning

and decide how you want the table to look The following options are available for setting

CSS classes:

Odd row class: This sets the styles for odd-numbered rows

Even row class: This sets the styles for even-numbered rows

Hover class: This determines how you want a row to look when the mouse hovers

over it

Select class: This styles the currently selected row

All these classes are optional, and you can set them later in Code view, but it’s easier to

create skeleton style rules first I have created some simple styles in spry_table.css,

which you can find in examples/ch19 The rules look like this:

Trang 7

th, td {padding:3px 10px;

}

th {cursor:pointer;

}.odd {background-color:#EEE;

}.even {background-color:#E8F2F8;

}.hover {cursor:pointer;

background-color:#B4C6DB;

}.selected {color:#FFF;

background-color:#999;

}

#details, #spryTable {float:left;

font-size:85%;

}

#spryTable {width:350px;

}

#details {width:450px;

margin:15px 0 0 30px;

}

dl {width:600px;

font-size:85%;

}

The odd rows will have a light gray background, and the even rows will have a light blueone Spry tables are interactive but don’t use <a> tags, so you need to change the cursorexplicitly to look like a hand when the mouse pointer passes over a table row Spry appliesthe setting for Hover class only over table rows, so you must create a separate rule tochange the cursor for table headers The color I have chosen for table rows when themouse passes over them is dark blue, with white text on a dark gray background for theselected row

Figure 19-5 shows the simple Spry table and detail region that you’ll build in the next ple of exercises Clicking the Thumbnail or Caption column header reorders the rowsaccording to which column you clicked The main image and description are displayed in aSpry detail region floating alongside the table and are automatically updated depending

cou-on the currently selected row—all without the need to refresh the page

Trang 8

Figure 19-5 A Spry table can be sorted and display related information in a detail region without

reloading the page

This exercise shows you how to create a Spry sortable table to display selected columns

from a data set The instructions form the basis for creating any Spry data set They assume

you created the ch19_gallery table and gallery_eng.php in the previous exercises If you

don’t have a copy of gallery_eng.php, use gallery_eng.php in examples/ch19

1.Save gallery_eng.php as spry_table.php in workfiles/ch19, and attach

spry_table.css in the examples/ch19 folder (attaching a style sheet was covered

in Chapter 4)

2.Click the Spry Data Setbutton in the Sprytab of the Insertbar, as shown in the

fol-lowing screenshot, or choose Insert ➤Spry ➤Spry Data Set

Creating a sortable table

19

Trang 9

As shown in the preceding screenshot, there are five options:

Select Data Type: The drop-down menu offers a choice of HTMLand XML Thisalways defaults to HTML

Data Set Name: Dreamweaver automatically populates this with ds1,ds2, and so

on As with recordsets, it’s better to choose a more descriptive name The valueinserted here is used as a JavaScript variable, so it must not begin with a num-ber, and it cannot contain any spaces, hyphens, or other punctuation apart fromthe underscore(_)

Detect: This is displayed only when Select Data Typeis set to HTML It determinesthe HTML structures that the wizard uses to detect the data source The default

isTables The other options are Divs,Lists, and Custom.Specify Data File: Use the Browsebutton to navigate to the file that contains thedata source This can be either an external file or the current file

Design time feed: This option caters for the situation where the actual data file isgenerated dynamically and not available on the development computer.Clicking this link displays a dialog box where you can specify a static file thatcontains dummy data in the same format as the actual data file

Enter dsPhotosin the Data Set Namefield, and use the Browsebutton to select thecurrent file, spry_table.php The Data Selectionfield of the wizard should displaythe image of Buckingham Palace and St James’s Park, together with its thumbnail,caption, and description

4.To select the data to be used in the data set, you need to select a data container, inother words, the table you created earlier There are two ways of doing this Eitheryou can click the yellow right-facing arrow at the top-left of the data container inthe Data Selectionfield or you can select its name from the Data Containersdrop-down menu at the top-right of the Data Selectionfield Use either method to selectthe ENGdata table

The wizard should now look like Figure 9-6 The Data Selection field shows

a visual representation of the data set, while the Data Preview field shows the raw data

3.This launches the Spry Data Set wizard (see Figure 19-6) When it first loads, thewizard looks like a vast empty space For it to spring to life, you need to specify thedata source in the fields at the top of the dialog box

Trang 10

Figure 19-6 The first step of the Data Set Wizard selects data from the original source.

19

5.Click Nextto move to the next step in the wizard (see Figure 19-7) This is where

you configure the data

The Advanced data selectioncheckbox at the bottom left of the wizard is

used only when you use other HTML structures to define the data

con-tainer Selecting the checkbox enables the Row Selectors and Column

Selectors fields, where you list the HTML elements and class names that

identify the rows and columns of the data set.

Trang 11

The Column Namefield at the top of the dialog box displays the name of the umn currently selected in the Data Previewfield By default, Dreamweaver uses thenames in the first table row However, if the first row contains data instead ofheader names, deselect the checkbox labeled Use first row as headerat the bottomleft of the dialog box This changes the column names to column0,column1, and so

col-on You can edit these generic names in the Column Namefield Names taken fromthe data table itself cannot be edited

The Typedrop-down menu alongside the Column Namefield sets the data type Bydefault, everything is treated as a string To change the data type, select the column

by clicking it in the Data Previewfield, or use the left and right arrows to the left ofthe Column Namefield The available options are string,number,date, and html Thefirst three affect the sort order of the column The final one, html, should be usedfor data that includes HTML tags If you fail to do so, the HTML tags will be dis-played in the web page rather than be used to structure the data

Most of the options in the Other Optionssection are self-explanatory You can selectone of the columns to sort the data in ascending or descending order, change the

Figure 19-7 The second step of the Spry Data Set wizard configures the data.

Trang 12

The final option, Disable Data caching, makes the web page more responsive to

changes in the original data By default, the data set remains in the browser’s cache

and isn’t updated when changes are made to the data source If you select this

checkbox, you need to enter in the Autorefresh datafield how frequently the web

page should check the original data source The value needs to be expressed in

mil-liseconds, so entering 60000in this field would check the original data source once

a minute

There is no option to exclude specific columns from the final data set, although it’s up

to you which columns to display in the web page However, it’s inefficient to include

large amounts of redundant data in a data set, so you should take this into account

when designing the original data container and include only data that you want to use

6.Select the Descriptioncolumn by clicking it in the Data Previewfield, set the Type

drop-down menu to html, and then click Nextto move to the final step of the

wiz-ard, which is shown in Figure 19-8

19

Figure 19-8 The final step of the Spry Data Set wizard lets you display the data in a variety of formats.

7.The final step has four display options, as well as the option not to insert any HTML

For this exercise, select the Insert tableradio button, and then click the Set Up

Trang 13

but-8.This opens the Spry Data Set – Insert Tabledialog box, as shown here:

The layout and functionality of the dialog box should be immediately familiar fromother parts of Dreamweaver You can remove a column by selecting it and clickingthe minus button; and if you change your mind, restore it using the plus button

By default, each column is sortable when its header is clicked If you don’t want acolumn to be sortable, select the column name and deselect the checkbox at thebottom of the Columnsarea

The remaining options set the CSS classes discussed earlier and let you update one

or more detail regions when a row is clicked

The table in Figure 19-5 displays just the Thumbnailand Captioncolumns, so light the other two and delete them Set the class drop-down menus to match theclasses in spry_table.css (you might need to select the class name twice, becausethe menus appear to be temperamental), and select the checkbox labeled Updatedetail regions when row is clicked This will be used to display the main image anddescription for each row in the table The dialog box should now look like this:

Trang 14

high-9.Click OKto close the dialog box This takes you back to the Spry Data Set wizard If

you’re unsure about any of the settings, click Previousto return to the earlier steps

of the wizard, and make any changes Otherwise, click Doneto close the wizard and

create the Spry data set and its associated Spry table

10.Save spry_table.php, and click OKto copy the Spry dependent files to your Spry

assets folder The page should now look like Figure 19-9 As you can see, a new

table has been added, similar to the one built from the PHP recordset

19

Figure 19-9 In Design view, a Spry table gives no real indication of what it will look like in a browser.

11.Click the Live Viewbutton to see what the page will look like in a browser It should

look similar to Figure 19-5 minus the image and description We’ll add them in a

moment, but first test the page by running the mouse over the rows and clicking

the column headers to sort the data The important thing to notice is that only the

thumbnails and captions are displayed; the unstyled HTML table being used as the

data source has been removed from the DOM

12.Deactivate Live view, and press F12/Opt+F12 to view the page in a browser As long

as JavaScript is enabled, it should look the same Right-click to select the option to

view the page’s source code The original HTML data source is still there, so the

page remains accessible to search engines and anyone viewing it with JavaScript

disabled The code generated by Dreamweaver uses the data in the HTML table to

populate the Spry table, and then hides the HTML table

Check your code, if necessary, against spry_table_01.php in examples/ch19

Displaying related data in a Spry detail region

A Spry table is basically a repeat region applied to a single table row However, instead of

using PHP to generate the other rows on the web server, it uses JavaScript to manipulate

the DOM inside the browser An advantage of doing this is that Spry can respond to mouse

events, such as moving over an element or clicking a table cell By creating a Spry detail

region, you can change its contents in response to such events Adding a detail region is

Live view processes only the current page through the testing server, so you can use it to

view the output of a Spry data set only if the data source is in the same page If you want

to use Live view to test a Spry data set that uses a dynamically generated data source in

an external page, load the page that generates the data source into a browser, and save

it as a static HTML file Use the static file for testing, and then switch back to the dynamic

data source when deploying the site on the Internet.

Trang 15

This exercise builds on the preceding one by adding a Spry detail region to display themain image and description when you click the related table row Continue using the samepage, or copy spry_table_01.php from examples/ch19, and save it in workfiles/ch19 asspry_table.php.

1.In spry_table.php, click anywhere in the second row of the table The <div>and

<tr> tags in the Tag selector at the bottom of the Document window are lighted in orange, indicating that they contain Spry data set code

high-2.Select the <div>tag, right-click, and select Set IDfrom the context menu Set the ID

to spryTable This is one of the style rules defined in spry_table.css It floats the

<div> left and sets its width to 350 pixels

3.With the <div> still selected, press the right arrow key once to move the insertionpoint outside the <div>

4.To display the description, you need to create a Spry detail region Click the SpryRegionbutton on the Sprytab of the Insertbar, as shown in the following screen-shot, or select Insert ➤Spry ➤Spry Region

5.This opens the Insert Spry Regiondialog box, as shown here:

The options let you choose a <div> or <span> as the container Most of the time,you’ll want to use a <div>, unless you want the region to appear inline You alsohave the choice of Regionor Detail Region The link at the bottom of the dialog boxopens the Dreamweaver help files to explain the difference Basically, a Spry region

is used to display multiple elements from a data set, such as a table A Spry detailregion gives you access to the currently selected element within the data set In thiscase, you’re going to display the main image and description of whichever thumb-nail or caption the user clicks in the table

The remaining options in the dialog box let you choose the data set if there’s more

Adding an updatable detail region

Trang 16

or to replace it Since nothing is currently selected in spry_table.php, the Wrap

selectionand Replace selectionoptions are grayed out

Use the settings shown in the preceding screenshot, and click OK

6.Dreamweaver inserts the Spry region with placeholder text, as shown here:

19

7.Open the Bindingspanel As you can see from the preceding screenshot, dynamic

objects for Spry data set values are listed in the same way as for a recordset or in

an XSLT fragment At the bottom of the list are three Spry data objects that can be

used to get access to the row ID, current row ID, and row count

The data objects that you’re interested in at the moment are Imageand Description

Select Image, and use it to replace the placeholder text in the Spry detail region

You can either drag and drop it or use the Insert button at the bottom of the

Bindingspanel

8.With the Image dynamic placeholder still selected, select Paragraph from the

Formatdrop-down menu in the HTMLview of the Property inspector

9.The data in the Descriptioncolumn is already formatted in paragraphs, so you need

to move the insertion point outside the closing </p> tag but remain inside the Spry

detail region <div> So, select <p>in the Tag selector, and press your right arrow

key once Then insert Descriptionfrom the Bindingspanel

10.You now need to apply an ID to the Spry detail region <div> Select <div>in the Tag

selector, right-click, and select detailsfrom Set IDin the context menu

11.The page should now look like this (if you have a small monitor, the details <div>

might be forced down below the <div> that contains the Spry table):

In Design view, it still looks very unimpressive, but when you save the page and test

it in a browser, it should look like Figure 19-5 and be fully interactive

Trang 17

Creating a master-detail set in a single operation

Adding a Spry detail region to a table, as you have just done, creates a master-detail set.However, one of the other options in the final step of the Spry Data Set wizard also cre-ates a master-detail set in a single operation What’s more, it comes with its own stylesheet, speeding up development and deployment considerably The following exercisedescribes how to set up the options for a master-detail set Since you already have a dataset in spry_table.php, you could delete the Spry table and detail region, and double-click dsPhotosin the Bindingspanel to relaunch the data set wizard and skip to the finalstep However, let's build the master-detail set from scratch to practice all three steps ofthe wizard

This exercise guides you through the Spry Data Set wizard to create a master-detail set in

a single operation Since the first two steps of the wizard were described in detail in the

“Creating a sortable table” exercise, I’ll keep the instructions for defining the data sourcebrief and concentrate on the final step This exercise assumes you have created thech19_gallery table and gallery_jpn.php, as described earlier in the chapter

1.Save gallery_jpn.php as master_detail.php in workfiles/ch19

2.In master_detail.php, launch the Spry Data Set wizard from the Sprytab of theInsertbar or the Insertmenu

3.In the first step of the wizard dialog box, use the following settings:

Select Data Type:HTMLData Set Name:dsPhotosDetect:Tables

Specify Data File:master_detail.phpData Containers:JPNdata

Just to introduce a little variety, I have chosen JPNdataas the source for the dataset The fact that I have used the same name as before for the data set, dsPhotos,doesn’t matter The data set is being used in a different page, so there is no con-flict As you’ll see later in this chapter, you can use Spry to change the data sourcedynamically

4.Click Nextto move to the second step of the data set wizard

5.Select the Descriptioncolumn, and set the value of Typeto html Leave the otheroptions at their default settings, and click Nextto move to the final step of thewizard

6.Select the Insert master/detail layoutradio button, and click the Set Upbutton side to open the following dialog box:

along-Setting the options for a master-detail set

Trang 18

The Master Columnsfield determines which columns you want to display as a

click-able list on the left of the page For this exercise, you’re going to use the Caption

column However, at least one column must always be selected in the Master

Columnsfield, so you can’t delete Thumbnailwithout first adding Caption

7.Click the plus button above the Master Columnsfield, select Captionfrom the Add

Columns dialog box that opens, and click OK This adds Caption to the Master

Columnsfield

8.You can now safely select Thumbnail in the Master Columns field, and click the

minus button to remove it

9.The Detail Columnsfield determines what to display in a box on the right side of the

page when one of the items is clicked in the list on the left of the page Since

Captionis used in the Master Columnslist, select Captionin the Detail Columnsfield,

and click the minus button to remove it

10.This leaves Imageand Descriptionin the Detail Columnsfield You can select how the

content will be displayed by selecting a value from the Container Typedrop-down

menu at the bottom of the dialog box The available options are <DIV>, <P>,

<SPAN>, and <H1>through <H6>

Select Image, and set the value of Container Typeto <P>

11.The Descriptioncolumn is already formatted as HTML, so set its Container Typeto

<DIV>

12.Click OKto close the Spry Data Set – Insert Master/Detail Layoutdialog box, and then

click Doneto close the wizard

13.Save master_detail.php, and click OK when prompted to copy the dependent

files to your Spry assets folder

19

Trang 19

14.Press F12/Opt+F12 to test the page in a browser There you have a simple, but gantly designed master-detail set, as shown in Figure 19-10 As before, Spryremoves the original HTML table from the DOM, but it remains in the underlyingHTML code for search engines and anyone with JavaScript disabled to access.You can check your code, if necessary, against master_detail.php in examples/ch19.

ele-Figure 19-10 The Spry Data Set wizard creates a master-detail set in just a few minutes.

Displaying a data set as a list

Dreamweaver can create four types of lists from a Spry data set: unordered (<ul>),ordered (<ol>), definition (<dl>), and drop-down menus (<select>) The way you createthem is similar to a detail region by selecting a button in the Sprytab of the Insertbar orusing an option on the Insert➤Sprymenu In other words, the data set must already exist

A list must be inside a Spry region, which either you can create first or you can leave it up

to Dreamweaver to wrap the list in a Spry region when you have finished

Unordered and ordered lists have only two options: the data set and the name of the umn that you want to display Definition lists and drop-down menus have an extra option

Trang 20

col-drop-down menu when building the photo gallery later, but let’s look briefly at creating a

Spry definition list To avoid the need to go through the Spry Data Set wizard again, let’s

adapt spry_table.php from earlier in the chapter

This exercise shows you how to display the Caption and Description columns of the

dsPhotos data set as a Spry definition list The result won’t look very elegant, but the

pur-pose is simply to demonstrate how to create a list with Spry Use spry_table_02.php in

examples/ch19 if you don’t have your own copy of the file

1.In spry_table.php, delete the Spry table and detail region, but leave the original

HTML table intact This leaves you with the Spry data set definition and all the

external files still attached

2.Save the page as spry_list.php

3.Click the Spry Repeat Listbutton in the Sprytab of the Insertbar, as shown in the

following screenshot, or select Insert ➤Spry ➤Spry Repeat List

4.This opens the Spry Repeat Listdialog box, as shown here:

The Container tagdrop-down menu contains the following four options:

UL (Unordered List): This creates an unordered list using <ul> tags and populates

the <li> tags with the values stored in the column selected as Display column

Only one column can be selected

OL (Ordered List): This creates an ordered (numbered) list using <ol> tags In

other respects, it’s identical to the previous option

DL (Definition List): This creates a definition list using <dl> tags When you select

this option, the Display columnoption is replaced by DT Columnand DD Column,

which let you choose what to display in the <dt> and <dd> tags

Creating a Spry definition list

19

Trang 21

SELECT (Drop-down List): This creates a drop-down menu using <select> tags.When you select this option, a Value columnoption is added at the bottom ofthe dialog box Display columndetermines the value displayed in the drop-down,and Value columnsets the value attribute of each <option> tag You’ll see this inoperation when building the Spry gallery later in the chapter.

Whichever option you choose for Container tag, the Spry Data Setoption selects thedata set to be used There’s only one data set on the current page, so it’s selected

As you can see from the preceding screenshot, Dreamweaver has inserted a <div>

on lines 57–62, and set the spry:region property to dsPhotos, the name of thedata set to use

The opening tag of the definition list on line 58 contains the spry:repeatchildrenproperty, which is also set to dsPhotos This tells the browser to loop through thedsPhotos data set for each child element of the <dl> tag—in other words, the <dt>and <dd> tags

Lines 59–60 insert {Caption} and {Description} data objects in the <dt> and <dd>tags, respectively

Dreamweaver does all this coding for you automatically, so you don’t need tobother about it unless you want to start using Spry in more sophisticated ways

Sometimes, Dreamweaver fails to prompt you to add a Spry region when you click OKto close the Insert Spry Repeat Listdialog box If this happens, select the definition list, and click the Spry Region button on the Insertbar, or select Insert

➤Spry➤Spry Region Set Containerto DIV,Typeto Region,Spry Data Setto the same data set as the definition list uses, and select the option to wrap the cur- rent selection.

Trang 22

6.Save spry_list.php, and press F12/Opt+F12 to view the page in a browser It

should look like Figure 19-11

You can check your code, if necessary, against spry_list.php in examples/ch19

Figure 19-11 The contents of the Spry data set are now displayed as a definition list.

Understanding the Spry data code

I don’t intend to go into great detail about how the code works The whole idea of the Spry

Data Set wizard is to make it easy to use Ajax without needing to become a JavaScript guru,

but it does help to recognize the code and have a basic understanding of what it’s for

The table and detail region in spry_table.php use remarkably little code, as you can see

from the following listing (all the Spry code is highlighted in bold):

<div id="spryTable" spry:region="dsPhotos">

<tr spry:repeat="dsPhotos" spry:setrow="dsPhotos" spry:odd=

"odd" spry:even="even" spry:hover="hover" spry:select="selected">

Trang 23

Even if you don’t know how it works, the Spry syntax is easy to follow Everything beginswith spry: followed by the name of a property and its value The property names are allvery intuitive: region, sort, repeat, and so on.

Take the code in the second table row It begins with spry:repeat="dsPhotos" This turnsthe row into a repeat region that draws data from the dsPhotos data set The spry:setrowproperty controls the display in the detail region When the row is clicked, Spry sets it asthe current row, which sends a message—or triggers an event, to use the correct termi-nology—that tells any dsPhotos detail region to update its contents

The data objects that hold the contents are in curly braces So, {Description} tells thebrowser to display the current description

What’s the difference between repeat and repeatchildren?

If you’re interested in taking Spry further, look more closely at the code in the Spry tableand the Spry definition list Both use Spry repeat regions, but there’s a subtle differencebetween them

The repeat region in the table is defined in the <tr> tag of the second row like this:

<tr spry:repeat="dsPhotos" spry:setrow="dsPhotos" spry:odd="odd" ➥spry:even="even" spry:hover="hover" spry:select="selected">

In the definition list, on the other hand, spry:repeatchildren repeats all the children of

a given element for each row in a data set The property is defined in the <dl> tag, which

If you forget to set one of the classes in a Spry table, you can easily edit the repeat row

by adding spry:odd, spry:even, spry:hover, or spry:select and the name of the class Dreamweaver code hints speed up the process by displaying the available options after you type spry:in Code view.

Trang 24

has two children: <dt> and <dd> As a result, Spry creates one definition list with a <dt>

and <dd> pair for every row in the dsPhoto data set

So, the difference can be summarized as follows:

spry:repeat repeats the element in which it is declared

spry:repeatchildren doesn’t repeat the element itself but does repeat its

chil-dren

Because Spry manipulates the content in the browser window without creating any

under-lying source code for you to inspect, it can sometimes be difficult to grasp the difference

between what’s happening For example, if you change the code in the <dl> tag from

spry:repeatchildren to spry:repeat, the output seems to be identical However, if you

create a style rule to add a visible border around a definition list, the difference becomes

obvious With spry:repeatchildren, there’s a single border around the list, but with

spry:repeat, you get a border around each list item (see Figure 19-12) In other words,

the <dl> element is also repeated, so you end up with eight definition lists instead of one

Figure 19-12 Using spry:repeat with the <dl> tag creates a separate definition

list for each row of the data set

This might tempt you to remove the Spry property from the <dl> tag and use spry:repeat

directly on the <dt> and <dd> elements like this:

<dl>

<dt spry:repeat="dsPhotos">{file}</dt>

<dd spry:repeat="dsPhotos">{caption}</dd>

</dl>

Figure 19-13 shows what happens—all the <dt> elements are repeated first, followed by

all the <dd> elements

19

Trang 25

Figure 19-13 Using the wrong type of Spry repeat region brings unwanted results.

You get equally undesirable results if you use spry:repeatchildren in the <tr> tag of thetable Instead of eight table rows with two table cells each, you get one table row with

16 table cells

Switching data sets dynamically

The pages you have built so far in this chapter use two data sources, ENGdata and JPNdata.Rather than display them in separate pages, let’s switch between them using a Spry selectlist This uses an HTML <select> element to create a drop-down menu The <option> tagsare populated automatically by a Spry data set, in the same way as the definition list thatyou built in the “Displaying a data set as a list” section earlier in the chapter However, ithas the added advantage that you can use it to dispatch information that other Spry com-ponents can respond to As a result, you’ll not only be able to display the main images anddescriptions without needing to reload the page, but you’ll also be able to switch betweenthe two sets of photos without reloading, making a smooth user experience

To save time, I have created a page (gallery_select_start.php in examples/ch19) thatbuilds an HTML data source containing both sets of photographs in a single table, with anextra column for the category to which each photo belongs The page is laid out the sameway as spry_table.php earlier in the chapter with the thumbnails and captions in a Sprytable on the left and the image and description in a Spry detail region on the right Belowthat are two tables that act as the HTML data containers The first one has an ID calledphotos; it acts as the data container for the gallery The second table is called galleries.This will be used as the data container for the drop-down menu; the left column identifiesthe categories, and the right one shows the values that will be displayed in the menu

Filtering a Spry data setSpry data sets support two types of filters: destructive and nondestructive A destructive filter

removes elements permanently from a data set For example, if you use a destructive filter to

Trang 26

remove the Japanese photos from the data set, the only way to gain access to the Japanese

photos is to rebuild the data set A nondestructive filter, on the other hand, removes the

ele-ments temporarily, so this is the type of filter you need to switch between the two sets

You create both types of filters the same way by defining a function that determines

whether to reject or include a row in the filtered set The function takes three arguments:

the data set, the current row, and the row number If the data in the row conforms to your

filter criteria, the function must return the row Otherwise, it must return null

To apply the filter, you pass the name of the filter function to the data set’s filterData()

method for a destructive filter or to its filter() method for a nondestructive filter

The following exercise shows you how to apply a nondestructive filter to the dsPhotos

data set in gallery_select_start.php

1.Open gallery_select_start.php in examples/ch19, and save it as

gallery_select.php in workfiles/ch19 When Dreamweaver asks whether you

want to update the links, click No You can close gallery_select_start.php,

because you don’t need it any more

2.Press F12/Opt+F12 to launch gallery_select.php in a browser to make sure that

it’s working correctly

If the browser displays a message saying it failed to retrieve the data set, locate the

following line of code (it should be on or around line 50):

var dsPhotos = new Spry.Data.HTMLDataSet( / /examples/ch19/null, ➥

"photos");

Change it to this:

var dsPhotos = new Spry.Data.HTMLDataSet(null, "photos");

When the data container is in the same page as the data set, the first argument to

HTMLDataSet() should be null Dreamweaver tries to add the path in front of null

if you tell it to update links or if you move the file within the Filespanel

3.Once you have confirmed that gallery_select.php is working correctly, you can

build the filter The code that creates the dsPhotos data set looks like this (it begins

around line 50):

var dsPhotos = new Spry.Data.HTMLDataSet(null, "photos");

dsPhotos.setColumnType("Description", "html");

JavaScript lets you define your own properties for objects, so let’s give dsPhotos a

gallery property with a default value of 'JPN' Add the following code to the

existing script block:

var dsPhotos = new Spry.Data.HTMLDataSet(null, "photos");

dsPhotos.setColumnType("Description", "html");

dsPhotos.gallery = 'JPN';

Trang 27

4.Now define the filter function Add the following code immediately after the line inthe preceding step:

function chooseSet(dataSet, row, rowNumber){

if (row['Category'] == dsPhotos.gallery) {return row;

}return null;

}

As explained earlier, the filter function takes three arguments; it returns rows thatmatch the filter criteria, and it returns null for nonmatching rows The conditionalstatement checks whether the value of Category in the current row is the same asdsPhotos.gallery If it is, the row is returned Otherwise, the filter function returnsnull You don’t need an else clause because return immediately brings the function

to an end The function never reaches return null if the condition equates to true

5.Finally, apply the filter nondestructively by passing the name of the function to thedata set’s filter() method The full code looks like this:

var dsPhotos = new Spry.Data.HTMLDataSet(null, "photos");

}return null;

}

dsPhotos.filter(chooseSet);

6.Save gallery_select.php, and test it in a browser Only the photos of Japan should

be displayed The photos of England have been filtered out of the data set, butthey’re not displayed in the data container either

7.Change the default value of dsPhotos.gallery in the third line of code to 'ENG'.Save the page, and view it again This time, only the photos of England should bedisplayed The next task is to make the switch dynamic with a Spry select list, whichyou’ll build in the next section

Check your code, if necessary, with gallery_select_01.php in examples/ch19

Creating a Spry select list

Creating a Spry select list uses the same technique as described earlier in the chapter in

“Displaying a data set as a list.” It involves the following three steps:

1.Create the data set that will be used in the Spry select list

2.Insert a Spry region bound to the data set

Trang 28

The data container for the Spry select list already exists in gallery_select.php, so you’re

ready to start

Because you’re going to use the data set to populate a select list, you don’t want the Spry

Data Set wizard to create any HTML However, the galleries table in gallery_select.php

doesn’t have any headings, so you need to assign your own Continue working with

gallery_select.php from the preceding exercise Alternatively, use gallery_select_01.php

in examples/ch19 (do not update the links when prompted by Dreamweaver)

1.Open gallery_select.php, and launch the Spry Data Set wizard

2.In the first step of the wizard, use the following settings:

Select Data Type:HTML

Data Set Name:dsGalleries

Detect:Tables

Specify Data File:gallery_select.php

Data Containers:galleries

The Data Previewfield should look like this:

Creating the Spry data set for the select list

19

3.Click Nextto move to the second step of the wizard

4.Currently, the first row of the table in gallery_select.phpis being used as headers for

the data set columns, so deselect the checkbox labeled Use first row as header This

changes the display in the Data Preview field by adding column0and column1at the

head of the two columns You can leave the generic names, but it makes the data

set a lot easier to use if you assign more meaningful names

5.Select column0, and type sourcein the Column Namefield

6.Select column1, type label in the Column Name field, and press Enter/Return to

effect the change The Data Previewfield should now look like this:

7.You don’t need any HTML created, so just click Doneto close the wizard

You can check your code, if necessary, against gallery_select_02.php in

Trang 29

You won’t see any change in gallery_select.php in Design view, but the dsGalleriesdata set is now listed in the Bindingspanel, and the data set definition has been added tothe <head> of the page.

Now that the data set has been created, you can insert the Spry select list

Using a Spry select list to change page content

Unlike a normal <select> element, when you insert a Spry select list into a page,Dreamweaver doesn’t prompt you to insert <form> tags at the same time This is becauseyou can use Spry to respond to changes in the selected option without the need to submit

a form All that’s necessary is to add an onchange event handler to the select list This patches details of the selected item to other Spry elements, updating the page in the sameway as clicking a row in a Spry table I’ll explain how it works in more detail when you addthe onchange event handler But first, let’s insert the Spry select list

These instructions show you how to add a Spry select list to gallery_select.php to play the details of the available photo galleries It draws its data from the dsGalleriesdata set that you created in the preceding exercise Continue working with the same page

dis-as before Alternatively, use gallery_select_02.php in examples/ch19

1.In Design view, select the spryTable <div>, and press your left arrow key to movethe insertion point to the top of the page If you check in Split view, the insertionpoint should be between the opening <body> tag and the opening tag of the <div>

2.Click the Spry Regionbutton on the Insertbar, or select Insert➤Spry➤Spry Region

3.In the Insert Spry Regiondialog box, use the following settings, and then click OK:Container:DIV

Type:RegionSpry Data Set:dsGalleries

This creates a Spry region and primes it to use the correct data set for the select list

4.The <div> created by the Insert Spry Regiondialog box contains placeholder text.Leave this selected, and insert the Spry select list by clicking the Spry Repeat Listbutton on the Spry tab of the Insertbar or by selecting Insert ➤ Spry ➤ SpryRepeat List

5.In the Insert Spry Repeat Listdialog box, use the following settings, and then click OK:

Inserting a Spry select list to display the photo galleries

Trang 30

This draws the data from the dsGalleries data set and uses the label column to

determine the text shown by each option and the source column to set the

option’s value attribute

6.The placeholder text should have been replaced by a select menu element Change

the name of the menu element in the Property inspector from the default value,

select, to selectGallery

7.Let’s add a label to the select menu Press your left arrow key to move the insertion

point in front of the menu element Then click the Labelbutton in the Formstab of

the Insertbar, as shown in the following screenshot Alternatively, select Insert➤

Form➤Label

This opens Split view with the insertion point between two <label> tags Type

Select galleryfollowed by a colon and a space Then edit the opening <label> tag

to add the for attribute, and set its value to selectGallery Click back in Design view,

or press F5 to view the change The page should now look like this:

8.Save gallery_select.php, and test it in a browser In most browsers, the

drop-down menu should display Englandby default However, Internet Explorer doesn’t

play ball and displays the last item instead—in other words, Japan

9.To fix the problem in Internet Explorer, you need to use the Spry equivalent of a

conditional statement You indicate a condition by adding the spry:choose

attrib-ute to the parent element—in this case, the <select> tag, which you need to

amend like this:

<select name="selectGallery" id="selectGallery" ➥

spry:repeatchildren="dsGalleries" spry:choose="spry:choose">

10.Internally, a Spry data set is like a database recordset, and each row has an ID

called ds_RowID, rather like a database primary key Spry keeps track of the

cur-rently selected row through another property called ds_CurrentRowID When the

data set is first created, ds_CurrentRowID is set to the first row So, to display the

first <option> element correctly, you need to check whether ds_RowID and

19

Trang 31

ds_CurrentRowID are the same If they are, you want to add selected="selected"

to the <option> tag

To create a condition in Spry, you use the spry:when attribute Amend the

<option> tag like this:

<option value="{source}" spry:when="{ds_CurrentRowID} == {ds_RowID}"

selected="selected">{label}</option>

11.Although this adds selected="selected" to the <option> tag when the two IDsare equal, it has the undesired side effect of preventing any other <option> tagsfrom displaying So, you need to add another <option> tag to display the remain-ing values This uses the spry:default attribute like this:

<option value="{source}" spry:default="spry:default">{label}</option>

12.The completed <select> list looks like this:

<select name="selectGallery" id="selectGallery" ➥spry:repeatchildren="dsGalleries" spry:choose="spry:choose">

<option value="{source}" spry:when="{ds_CurrentRowID} == {ds_RowID}" ➥selected="selected">{label}</option>

<option value="{source}" spry:default="spry:default">{label}</option>

</select>

13.If you test the page in Internet Explorer, the correct item should now display whenthe page first loads It also works correctly in other modern browsers However,nothing happens yet if you select Japan You’ll fix that next But first, check yourcode, if necessary against gallery_select_03.php in examples/ch19

The Spry select list works like a normal <select> element The value of label in the eachrow of the data set is displayed as text in a drop-down menu, and the value of source isstored in the value attribute of the corresponding <option> tag To display the correct set

of photos, you need to change the value of dsPhotos.gallery whenever an option isselected in the drop-down menu You do this by creating a function that resets andrefilters the dsPhotos data set and by attaching the function to the onchange attribute ofthe <select> menu, as shown in the next exercise

The following instructions show you how to reset the data set that contains details of thephotos to be displayed Continue working with gallery_select.php Alternatively, usegallery_select_03.php in examples/ch19 All the work needs to be done in the underly-ing code, so roll up your sleeves and switch to Code view

1.Amend the <select> tag to pass the value of the currently selected item in thedrop-down menu to an event handler called changeSet() like this:

<select name="selectGallery" id="selectGallery" ➥spry:repeatchildren="dsGalleries" spry:choose="spry:choose" ➥

onchange="changeSet(this.value)">

Wiring up the Spry select list

Trang 32

3.It’s not important where you define changeSet() within this code block, but to

keep things grouped together logically, insert some space after the code shown on

line 60 of the preceding screenshot, and enter the following code:

This takes the value passed to the function and assigns it to dsPhotos.gallery So,

if Japanis chosen from the drop-down menu, dsPhotos.gallery is reset to 'JPN'

The next line applies chooseSet() as a nondestructive filter in the same way as

when the page first loads Since chooseSet() filters the data set according to the

value of dsPhotos.gallery, this refilters dsPhotos and selects only the Japanese

photos

4.Save gallery_select.php, and test the page in a browser When you select Japan

from the drop-down menu, the thumbnails and their associated captions should

change However, the image and description in the Spry detail region don’t update

until you click one of the thumbnails or captions This is because the changeSet()

event handler doesn’t broadcast the change to the detail region You need to reset

the data set’s current row number to 0 and then loop through each row until you

find the first one that belongs to the filtered set

5.Amend changeSet() like this:

var rows = dsPhotos.getData();

for (var i = 0; i < rows.length; i++) {

if (rows[i]['Category'] == set) {

By passing this.value as the argument, changeSet() obtains ENG or JPN from the

<option> tag You now need to define changeSet()

2.Scroll up to the section in the <head> of the page where the two Spry data sets are

defined It looks like this:

Trang 33

break;

} }

}

The first line of new code resets the current row number of the dsPhotos data set

to 0 The next line uses the getData() method to store the data set temporarily in

a variable called rows The loop then iterates through each row, checking the value

of the Category column and incrementing i by one each time As soon as it finds avalue that equals the value passed to changeSet(), it sets the data set’s current rownumber to i and brings the loop to an end with break

6.Save gallery_select.php, and load it into a browser Select Japanfrom the down menu, and the new gallery is displayed without needing to reload the page, asshown in Figure 19-14 Check your code, if necessary, against gallery_select_04.php

drop-in examples/ch19

Figure 19-14 The drop-down menu displays a new gallery without reloading the page.

Trang 34

Creating a Spry data set from XML

As I mentioned at the beginning of the chapter, originally Spry data sets could be created

only from XML Although Adobe now encourages the use of an HTML data source in

pref-erence to XML, you can still use an XML source You build a data set from XML through the

Spry Data Set wizard in very much the same way as with an HTML data source, but there

are some important differences, so this section gives a brief outline of the process It uses

an XML document called england.xml, which contains details of the eight photos of

England used in the preceding exercises

The structure of england.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>

<gallery>

<photo>

<file width="400" height="300">buck_palace.jpg</file>

<caption>Buckingham Palace and St James's Park</caption>

<description><![CDATA[<p>St James's Park

</p>]]></description>

</photo>

<photo>

<file width="374" height="283">countrygarden.jpg</file>

<caption>A typical English country garden in Oxford</caption>

<description><![CDATA[<p>The </p>]]></description>

</photo>

</gallery>

In other words, the details of each photo are in a top-level repeating node called <photo>

The file name is in a child node called <file>, which stores the image dimensions as

attrib-utes Two other child nodes, called <caption> and <description>, contain the remaining

details of the photo The <description> node uses a CDATA section, which permits the use

of HTML tags inside an XML text node

Using the Spry Data Set wizard with an XML document

The structure of england.xml is similar to the HTML table you created as a data source in

gallery_eng.php, but it contains no image tags, so the resulting Spry data set will need to

store the file name and the image dimensions separately

The following instructions show you how to create a Spry data set from an XML document

and then incorporate it in a master-detail set to display images by binding data to the

attributes of HTML tags Since the Spry Data Set wizard was covered in detail earlier in the

chapter, I’ll concentrate on the differences of working with an XML data source

1.Create a new page called spry_xml.php in workfiles/ch19 (You can also use an

.html file name extension, because no PHP is involved in this process.)

2.Launch the Spry Data Set wizard from the Spry tab of the Insert bar or the

Insertmenu

19

Trang 35

Figure 19-15 With an XML source, the first step of the data set wizard closely resembles working with an XSLT

fragment

3.In the first step of the wizard, select XMLfrom the Select Data Type drop-downmenu As soon as you do so, the Detectdrop-down menu disappears, and the DataSelectionfield changes to Row element

4.Change Data Set NametodsPhotos, and use the Browsebutton to set the SpecifyData Filefield to use examples/ch19/england.xml This populates the Row elementfield with a diagrammatic representation of the XML hierarchy in the same way asthe Bindingspanel does when you create an XSLT fragment (see Chapter 18)

5.In the same way as with an XSLT fragment, you need to select the repeating node,which is indicated by a small plus icon alongside a pair of angle brackets Selectphotoin the Row elementfield This now populates the Data Previewfield with rowsand columns representing the data set The first step of the wizard should now looklike Figure 19-15

Trang 36

Notice that the dimensions of the image are displayed as file/@height and

file/@width, indicating that they are attributes of the <file> node Only the file

names are shown, not the actual images, because the XML data source is text only

6.Click Nextto move to the second step of the wizard As you can see in Figure 19-16,

it’s almost identical to the second step for an HTML source You can’t change the

column names, and the options not to use the first row as headers and switch rows

to columns are not relevant to XML The other options are the same

7.Set Typeto numberfor file/@heightand file/@width; and for description, set Typeto

html Then click Nextto move to the final step of the wizard

8.The final step is identical to when you use an HTML data source Select the Insert

master/detail layoutradio button, and then click the Set Upbutton alongside

Figure 19-16 With XML, you cannot rename the column names.

Trang 37

9.I explained how the Spry Data Set – Insert Master/Detail Layoutdialog box works inthe “Setting the options for a master-detail set” exercise earlier in the chapter, so Iwon’t go into the details again Use the following settings, and then click OK.

10.Click Doneto close the wizard

11.Save spry_xml.php, and click OKwhen prompted to copy dependent files to yourSpry assets folder

12.Because the XML data source is a static file, you can use Live view to see the put It should look similar to Figure 19-10, only the file name is displayed instead of

out-an image You need to insert the image yourself out-and bind the Spry data to it

13.Turn off Live view It’s best to work in Split view so you can see what’s happening inthe underlying code

14.Select the {file}dynamic placeholder in Design view, and press Deleteto remove it.This leaves the insertion point between the <p> tags, which is where you want toinsert the image

15.Click the Imagesbutton in the Insertbar, or select Insert➤Imageto open the SelectImage Sourcedialog box

16.To get the correct path for the dynamic image, you need to use the same technique

as when you created the HTML data source at the beginning of this chapter.Navigate to the images/gallery folder, cut the value in the URLfield to your clip-board, and then select Data sourcesin the Select Image Sourcedialog box

17.Select file from the dsPhotos data set, and paste the path back in front of thedynamic placeholder, as shown here:

Trang 38

18.Click OKto close the Select Image Sourcedialog box, and set the alternate text to

<empty>when prompted

Notice that the code inserted in Code view uses {file} instead of

{dsPhotos::file} This is because it’s in a dsPhotos detail region The prefix isn’t

required when the data set is the same as that for the detail region

19.Finally, you need to bind file/@height to img.height, file/@width to img.width, and

captionto img.alt through the Bindings panel in the same way as you did for the

HTML image at the beginning of the chapter The code for the image tag should

end up looking like this in Split view:

19

20.Save spry_xml.php, and test it in Live view or a browser It should look the same as

Figure 19-10, except it uses the photos of England

You can check your code, if necessary, against spry_xml.php in examples/ch19

This example uses a static XML document However, you can also generate the XML data

source dynamically with PHP Details of how to do so are in the appendix

Trang 39

Validating pages that use Spry

If you submit a page that uses Spry to the W3C validator at http://validator.w3.org/,you get a series of errors saying, for example, that there is no attribute spry:region orspry:repeatchildren This happens even though Dreamweaver amends the <html> tag atthe top of the page like this:

<html xmlns="http://www.w3.org/1999/xhtml" ➥

xmlns:spry="http://ns.adobe.com/spry">

The code highlighted in bold declares spry as a namespace This tells the browser not toconfuse anything prefixed with spry: with standard HTML attributes or custom attributesfrom other namespaces, such as other Ajax frameworks While this prevents conflicts, it’snot sufficient for W3C validation You need to tell the validator where to find the Sprydocument type definition (DTD) by inserting an ENTITY declararation into the DOCTYPEdeclaration at the top of each page like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ➥

So, why doesn’t Dreamweaver add the necessary code? Figure 19-17 shows why InternetExplorer, Firefox, and Safari all fail to understand the <!ENTITY> declaration and display

%SPRY; ]> at the top of the page if you include it (see http://labs.adobe.com/technologies/spry/articles/validation/validating_spry.html)

Figure 19-17 Most leading browsers can’t cope with the code needed to ensure that Spry validates.

If W3C validation is a mandatory requirement for your website, you have two options:don’t use Spry, or remove the Spry markup from the page with Dreamweaver CS4’s newJavaScript Extractor

Trang 40

The JavaScript Extractor was covered in Chapter 8, but let’s put it to practical use

convert-ing the gallery you have worked on throughout this chapter

This brief exercise shows you how to extract the Spry markup from gallery_select.php

so that the page validates against W3C standards Continue using the same file as in

previ-ous exercises Alternatively, use gallery_select_04.php in exercises/ch19 as your

start-ing point

1.With gallery_select.php open in the Document window, select Commands ➤

Externalize JavaScript

2.Because the page has a php file name extension, Dreamweaver displays a warning

that it’s not recommended to run the command on pages with server-side code

and asks whether you want to proceed anyway The warning is there because the

JavaScript Extractor might not be able to identify the right elements to extract if

server-side code, such as PHP, and HTML are mixed within the body of the page

That’s not the case here, so it’s safe to go ahead Click Yes

3.In the Externalize JavaScript dialog box, select Externalize JavaScript and attach

unobtrusively As shown in Figure 19-18, Dreamweaver displays a list of all the

JavaScript elements that will be removed You want to remove all of them, so leave

everything selected, and click OK

Figure 19-18 The JavaScript Extractor identifies all the JavaScript elements and Spry markup

Converting the Spry gallery to use unobtrusive JavaScript

19

Ngày đăng: 12/08/2014, 13:22

TỪ KHÓA LIÊN QUAN