CL-HTTP Chapter 13: Dynamic Forms


Reference Manual | Prev: Chapter 12. W3P Presentation System | Next: Chapter 14. W4 Web Walker


Contents

  1. 13.1 Overview
  2. 13.2 Loading
  3. 13.3 Command Interfaces, Queries, and Forms
  4. 13.4 Presentation Types
  5. 13.5 HTTP Export and the Form Lifecycle
  6. 13.6 Validation and Automatic Retry
  7. 13.7 The Survey Facility
  8. 13.8 Subject-Line Commands
  9. 13.9 The Text View
  10. 13.10 Extending Dynamic Forms
  11. 13.11 Status and Futures

13.1 Overview

Dynamic Forms (DF) is a declarative form-processing engine layered over the W3P presentation system. You define queries (typed questions) and compose them into forms; the engine renders each form as an HTML page, accepts and validates the submitted values through W3P presentation types, re-presents the form with inline error guidance when values fail to parse, and runs your response function with the parsed values bound. The same form definition renders and parses in multiple views: the HTML view over HTTP and a text view suitable for electronic mail.

Dynamic Forms originated in the Communications Linker System (Comlink), where it processed both CLIM-presented forms and fill-out forms returned by electronic mail, and powered the White House electronic publication system beginning in 1992. This chapter documents the CL-HTTP port, which replaces the CLIM presentation substrate with W3P and makes HTTP the primary transport.

The main concepts:

Command Interface
A namespace that holds a table of queries, a table of forms, and optionally a set of subject-line commands. Command interfaces can inherit queries, forms, and commands from other command interfaces.
Query
A single typed question: a W3P presentation type plus instructions, a default, an error presenter, and per-view rendering parameters. Queries are defined once and shared across the forms of their command interface.
Form
An ordered collection of queries with instructions, HTML page parameters (title, heading, colors, buttons), an optional signature, and a response function that receives the parsed values.
View
The presentation medium. df:html-view renders and accepts over HTTP; ascii-email-view presents a form as fill-out text and parses answers from a message body.

The engine lives in the DYNAMIC-FORMS package (nickname DF). The form presentation type library that DF builds on is part of foundational W3P (Section 12.7), defined in the WWW-PRESENT (W3P) package and re-exported through DF, so applications can name every type with the df: prefix. Engine sources are under http:df;, with the optional survey facility in http:df;survey;.

13.2 Loading

Dynamic Forms is an optional system named DYNAMIC-FORMS, with the survey facility in a second system named SURVEY that loads after it. Applications that do not run surveys need not load the survey system.

Under LispWorks, the start script asks Include Dynamic Forms and Include Dynamic Forms Survey along with the other optional subsystems; answering yes to the survey question implies the base system. When building an image from the command line, pass the dynamic-forms and dynamic-forms-survey options after -dump-cl-http.

To load by hand in a running image:

(load "http:df;sysdcl.lisp")
(compile-system 'dynamic-forms :load t)

;; Optionally, the survey facility:
(load "http:df;survey;sysdcl.lisp")
(compile-system 'survey :load t)

13.3 Command Interfaces, Queries, and Forms

Defining a Command Interface

(df::define-command-interface "registration" ())

;; Inheriting the queries, forms, and commands of another interface:
(df::define-command-interface "conference" ("registration"))

define-command-interface name (&rest inherit-from) &key clear-form-structure import-queries shadow-queries import-forms shadow-forms creates or updates a command interface. Inheritance precedence is left to right, with local definitions always taking precedence. import-queries and import-forms take lists of (command-interface . names) for selective import.

Defining Queries

(df::define-query ("age" "registration")
  :presentation-type '(df:integer+ 1 120)
  :html-instructions "Your age in years?")

(df::define-query ("color" "registration")
  :presentation-type '(df:one-of ("Red" "Green" "Blue"))
  :default "Green"
  :html-instructions "Favorite color?")

The important define-query keywords:

:presentation-type
The W3P presentation type that renders the input widget and parses the submitted value. The argument is evaluated, so quote type specifiers.
:default
The default value, presented according to :provide-default.
:provide-default
How the default participates: :visible pre-fills the widget with the default; :invisible substitutes the default when the user leaves the query blank without showing it; :failure (the default) treats a blank answer as a parse failure and retries.
:response-function
An optional per-query function of (query query-value) that runs before the form response function.
:html-instructions, :html-extended-instructions
The question text shown above the input widget, and optional longer instructions.
:error-presenter
How parse failures are explained on retry: :normal or :unfilled.

Defining Forms

(df::define-form ("profile" "registration")
    "User Profile"                       ; the subject
    (:external t :export t)              ; form options
  :queries ("age" "color")
  :html-title "User Profile"
  :html-instructions "Tell us about yourself.")

define-form takes (name command-interface), a subject string (used as the page heading and the mail subject line), an options list, and keywords. The principal options and keywords:

:form-class
The form class; the default atomic-form requires all queries to parse before the response function runs. Plain form processes queries independently.
:external, :export
:external makes the form visible to users. :export exports the form's HTTP URL at definition time (Section 13.5): either t, or a list combining the URL overrides (:host, :port, :protocol, :directory, :type) with export arguments passed through to export-url, for example (:export (:keywords (:survey) :authentication-realm :staff)).
:queries, :required-queries
The ordered query names, and the subset that must be answered.
:response-function
A function of (form query-status-alist) run after all query values are accepted; defaults to default-response-function.
:html-title, :html-heading, :html-instructions, :html-buttons, :html-background-color ...
HTML page parameters. Derived HTML slots (such as the heading) are computed at definition time.

Two definition-time rules to remember:

13.4 Presentation Types

The form presentation type library that queries draw on -- strings and text, numbers and time, completion choices, network and location types -- is part of foundational W3P: see Section 12.7 for the catalog and each type's HTML rendering and parsing behavior. The types load with the server, without Dynamic Forms, and are re-exported through the DYNAMIC-FORMS package, so queries name them with the df: prefix as in the examples above.

In the textual (email) view, every type in the library also presents as fill-out text and parses its answer from the returned message; Section 13.9 documents the text view's present and parse loop.

13.5 HTTP Export and the Form Lifecycle

Export

;; Export a form's computed URL (or supply :export in define-form):
(http:export-dynamic-form (df::intern-form "profile" :command-interface "registration")
                          :keywords '(:registration)
                          :documentation "The user profile form.")

http:export-dynamic-form computes the form's URL from the command-interface and form names -- /registration/profile.html -- interns it as a url:http-dynamic-form, and installs the GET and POST responders. :recompute-url-p forces the URL to be recomputed; :recache-p forces the cached HTML slots to be recomputed.

Five keywords override the computed URL's components, each defaulting to the server standard: :host (default http:*http-host-name* or the local host), :port (default http:*standard-http-port*), :protocol (:http or :https, default http:*standard-protocol*), :directory (a string or list of strings, default the command-interface name), and :type (the URL extension, default "html"). Supplying any of them forces the URL to be recomputed; when :protocol differs from the default, the port falls back to the scheme's standard port unless :port is given. For example, (:export (:directory "custom" :type "form")) exports /custom/profile.form. These keywords work in define-form's :export list as well.

The standard export arguments -- :keywords, :documentation, :authentication-realm and :capabilities, :expiration, :language, :read-subnets/:write-subnets, :property-list, and the cache-control directives -- pass through to export-url and apply to the form's URL exactly as for any other export type. See also Appendix C under :html-dynamic-form.

GET: Rendering

A GET renders the complete page with df::write-form: document preamble, the form's color scheme and heading, instructions, the numbered queries with their widgets and defaults, and the reset/submit buttons. df::present-form renders only the <form> element, for embedding a form in another page's body.

All Dynamic Forms pages -- form pages, retry pages, confirmation pages, and survey acknowledgments -- are generated through the document look facility (html:with-document-look-html). Under the default look the output is a plain HTML5 document; when a site installs a look (for example by setting html:*standard-document-look*), every Dynamic Forms page automatically acquires the site chrome: stylesheet links, header and footer blocks, and the site signature, with no per-form configuration. The legacy color scheme slots (background, foreground, and link colors) are emitted as a per-page CSS <style> element in the document preamble, since HTML5 drops the body color attributes; the style element follows any look stylesheet, so per-form colors override the site look.

POST: Accepting and Responding

The POST responder accepts each submitted value through its query's presentation type, then runs the form's response function inside an environment that binds the parsed values. Response functions access values with df:bind-query-values:

(defmethod my-profile-response ((form df::form) query-status-alist)
  (df::with-form-response-function-environment (form query-status-alist)
    (df::bind-query-values (age color)
      (process-profile age color)
      :success)))

(df::define-form ("profile" "registration") "User Profile" (:export t)
  :queries ("age" "color")
  :response-function 'my-profile-response)

The response function returns a task status keyword that tells the HTTP layer how to complete the request:

:success
The engine writes the default confirmation page acknowledging the submitted values.
:failure
Some queries failed; the retry page has already been written (Section 13.6).
:responded
The response function wrote the complete HTTP response itself (survey receipts do this).
:error
A query or form response function signalled an error; the server reports an internal error for the form.

13.6 Validation and Automatic Retry

Every submitted value is parsed by its query's presentation type. When any value fails to parse -- an out-of-range integer, an unrecognized choice, a blank required answer -- the engine re-renders the whole form as the response instead of a confirmation:

The user corrects the failing answers and resubmits; a clean submission then completes normally. The machinery is df::retry-failed-queries, which response functions can also call directly with :query-default-alist (values to preserve), :query-parse-failure-alist, and :explanatory-message.

Customize the guidance per type by specializing w3p:describe-presentation-type or the type's presentation-type-pretty-name.

13.7 The Survey Facility

The SURVEY system adds hierarchically branching survey instruments with per-respondent response recording. A survey instrument is a form whose answers are recorded in a survey store keyed by respondent; branch rules over the answers select follow-up instruments that are presented on the receipt page.

Survey Stores

Responses persist through the survey-store protocol, keyed by a database keyword. The reference implementation is an in-image store:

(df:make-memory-survey-store :pets)

The protocol -- df:with-survey-store, df:with-survey-store-transaction, df:intern-survey-respondent, df:intern-survey-response (which merges answer alists across partial submissions), df:survey-response-answer-alist, df:survey-response-complete-p, df:note-survey-response-complete, and the map- operators -- is abstracted from the Comlink Statice interface, so a persistent database back end implements the same generic functions on its own store class.

Defining Survey Queries and Instruments

(df::define-command-interface "pets" ())

(df:define-survey-query ("s-email" "pets")
  :presentation-type 'df:email-address
  :html-question "Your email address?")

(df:define-survey-query ("s-pets" "pets")
  :presentation-type '((df:some-of ("Cat" "Dog" "Fish") :test equal))
  :set-type :unordered-set
  :html-question "Which pets do you have?")

(df:define-survey-instrument ("cat-followup" "pets") "Cat Follow-Up" ()
  :queries ("s-email" "s-cat-name" "s-cat-toys")
  :database :pets
  :html-title "Cat Follow-Up")

(df:define-survey-instrument ("pet-survey" "pets") "Pet Survey" ()
  :queries ("s-email" "s-pets")
  :database :pets
  :instrument-branches ((:if (s-pets (:intersection ("Cat"))) :select "cat-followup"))
  :dispatch-method :depth-first
  :html-title "Pet Survey")

(http:export-dynamic-form (df::intern-form "pet-survey" :command-interface "pets"))
(http:export-dynamic-form (df::intern-form "cat-followup" :command-interface "pets"))

Branch Rules

Each rule in :instrument-branches is (:if antecedent :select form-name). An antecedent is a query clause (query-name value-spec) or a boolean combination with :and, :or, and :not. The value specs:

value or (:equal value)
The answer equals value.
:null
The answer is empty.
(:member (value...))
The answer -- a single value -- is one of the listed values.
(:intersection (value...))
A multi-valued answer shares at least one value with the list. Use this, not :member, for some-of queries: :member tests the whole answer list against the values.
(:disjoint (value...)), (:every (value...))
A multi-valued answer shares no value with the list, or contains every listed value.
(:first-equal value), (:first-member (value...))
Tests on the first (highest-ranked) element of an ordered answer.

:dispatch-method selects among rules whose antecedents fire: :exclusive-branch (exactly one), :depth-first, :breadth-first, or the :random- variants. Equal predicates are merged across rules and truth values are cached per evaluation, so shared antecedents are computed once.

The Respondent's Journey

The standard response function records the answers under the respondent's identity -- taken from the instrument's email-typed query -- and writes a receipt page. When branch rules fire, the receipt explains that the survey is adaptive and embeds the follow-up instrument on the same page, with the respondent's email pre-filled. Partial submissions are merged and acknowledged with an invitation to answer the remaining questions; once df:check-survey-completion-status finds every branch complete, further submissions are acknowledged as already complete (unless df:*allow-revision-of-complete-survey-response* is set). df:apply-survey-continuation walks an instrument tree against the store, classifying each instrument as unanswered, partially answered, or complete -- the primitive behind follow-up computation that applications can reuse for reminder mailings.

13.8 Subject-Line Commands

Command interfaces can also parse and execute commands from a one-line string -- historically the Subject line of a mail message addressed to a Comlink mail server. Two grammars are provided; both are driven by df:parse-and-execute-subject-commands.

The Command Parser

Commands are defined against a command interface with df:define-df-command-string. Each syntax element is either a literal token (matched case-insensitively) or a (presentation-type &optional match tag) triple: the type parses the token, match constrains the parsed value (:any accepts anything), and tag names the value in the environment passed to the action function.

(defun server-help (path string index environment)
  "Describes the commands this server understands"
  (declare (ignore path index environment))
  (mail-command-documentation string))

(defun mailing-list-info (path string index environment)
  "Information about the named mailing list"
  (declare (ignore path index))
  (mail-list-information (cdr (assoc :mailing-list environment)) string))

(df:define-df-command-string "registration" ("Help") server-help)
(df:define-df-command-string "registration"
                             ("Information" ((df:delimited-string (#\space #\return)) :any :mailing-list))
                             mailing-list-info)
;; Execute the best match; T as the third argument simulates, printing the call instead.
(df:parse-and-execute-subject-commands "registration" "Information cl-http-www" nil)

The parser walks a grammar tree collecting every match, then executes the action of the match that consumed the most input. Action functions take (path string index environment); environment is the alist of tagged values. When no command matches, df::parse-command-no-match-found is signalled. A command interface searches its own commands and then those of the interfaces it inherits from. sp:document-grammar generates a command/documentation listing for help replies, and df:outline-transition-tree prints the grammar tree.

The Transition-Net Parser

The older grammar compiles a spec of presentation types and completion values into a transition net; each transition consumes one whitespace-delimited token. Entries are (presentation-type possible-values subtree . functions), and action functions take (path string index):

(df:define-subject-line-commands "registration"
  :transition-tree ((completion ("subscribe" "unsubscribe")
                                ((completion ("digest" "normal") nil set-subscription-mode))
                                handle-subscription)))

parse-and-execute-subject-commands uses the command parser when the interface has commands defined with define-df-command-string and falls back to the transition net otherwise. Parse failures inside the net signal df:subject-line-command-parse-error; df:subject-line-command-parsing-error-p distinguishes a user's mistaken command from a subject line that was never a command at all.

13.9 The Text View

The text view presents a form as fill-out text -- instructions, the form identifier line, each query with a =>QUERY=> marker, and the signature -- and parses a filled-in message string back into query values:

;; Present the form as text (a mail body) plus its subject line:
(df::present-form form df::+ascii-email-view+ stream)

;; Parse the returned text: values, the form, retry queries, and parse failures.
(df::parse-form message-string)

The parser locates the form from its identifier line, extracts each query's answer between its markers (tolerating quoting junk and re-flowed lines heuristically), and accepts each answer through the query's presentation type in the textual view. Parse failures are reported per query so a retry message can re-present the failing questions with the good answers pre-filled (df::present-text-retry-message). The mail transport that closes this loop -- sending the retry message and receiving the resubmission -- is deferred to the mail phase (Section 13.11).

13.10 Extending Dynamic Forms

New input widgets are new W3P presentation types. Define the type with w3p:define-presentation-type (usually inheriting from a type in the form library), a render method on accept-present-default for html-view, and an accept method for the submitted value; then export the name through the DYNAMIC-FORMS package. See Chapter 12 for the presentation-type substrate, and note the CLIM parameter-inheritance caveat at the end of Section 12.7 when a new type specializes a parameterized type's defaults.

13.11 Status and Futures

The HTML view, the survey facility, the subject-line command processor, and the text view's present and parse paths are complete. Planned work:


Reference Manual | Prev: Chapter 12. W3P Presentation System | Next: Chapter 14. W4 Web Walker