[Web-SIG] Form field dictionaries

Simon Willison cs1spw at bath.ac.uk
Fri Oct 24 11:25:29 EDT 2003

David Fraser wrote:
> Fine. So we need a clever way of providing them in either form. I think 
> using dictionaries for this is essential - even if it means defining a 
> single dictionary that remembers which fields are get and which are 
> post, and provides different wrappers to see the different elements.

I am convinced that the neatest way of handling this is to replicate 
PHP's form field dictionaries, in particular these three:

GET - the form data that came in via GET
POST - the form data that came in via POST
REQUEST - the above two dictionaries combined (POST over-riding GET)

However, there is one special case that needs considering: multiple form 
fields of the same name. For example, the following URL:


What should GET['a'] return? There are three possibilities: return a 
list (or tuple) containing 1 and 2, or return 1 (the first value) or 
return 2 (the second value). The first has a huge disadvantage in that 
all of a sudden accessing the GET dictionary could return a list or a 
string - code will then have to start checking the type of the returned 
data before doing anything with it. The second and third have the 
disadvantage that some form data gets "lost" by the dictionary.

PHP has an interesting way of dealing with this, based on special syntax 
used for the names of form elements. If you have two query string 
arguments of the same name, PHP over-writes the first with the second. 
However, if the form field names end in [] PHP creates an array of them 
instead. For example:


GET['a'] == 2


GET['a'] == [1, 2]

In fact, PHP extends this to allow for dictionary style data structures 
to be passed in from forms as well:


GET['a'] == {'first': 1, 'second': 2}

This is a pretty neat solution, but carries the slight disadvantage that 
information about the way an application is internally structured (i.e 
that it processes form input as a list or dictionary) is exposed in the 
application HTML. That said, from previousl experience with PHP it is an 
extremely powerful technique. For example, check out this example form 
for editing a blog entry:

<form action="updateentry.py" method="post">
<input type="hidden" name="id" value="43">
Title: <input type="text" name="entry[title]"><br>
Author: <input type="text" name="entry[author]"><br>
Entry: <textarea name="entry[body]"></textarea>

Submitting this form in PHP results in a dictionary style data 
structures called 'entry' being made available to the script, neatly 
encapsulating the data about the entry sent from the form.

I'm sure there's an elegant solution to all of this, but I'm not sure 
what it is :)

Simon Willison
Web development weblog: http://simon.incutio.com/

More information about the Web-SIG mailing list