An introduction to Populate

Overview

Populate was designed as a client-side, post-load method of populating HTML forms.

The advantages of this are:

  • HTML markup (presentation) can be kept separate from database-output (data)
  • Forms can be re-populated without lengthy page loads, for example, using AJAX

What this means in reality for the developer is that the actual HTML for form-heavy web pages need not be made fragile by iterspercing it with messy server-side logic, and pages can be developed, and redeveloped with more confidence and in a fraction of the time.

Populate supports:

  • Population of all HTML form control-types (ignores buttons)
  • Population of checkbox arrays and other non-standard UI controls
  • Full PHP naming and deep data structures

Being hierachical, the JSON format is particularly suited to working with how PHP handles form variables (also hierarchically), and Populate has been built with this inter-operatibilty in mind (see the last section on this page).

Basic Usage

You need to do 3 things to have Populate automatically fill an HTML form with the correct values:

  • Include the blank HTML form in the body of the page
  • Get the relevant form data, e.g. user information, into JSON format
  • Output the JSON format as the first agument of the Populate call

The basic form for using Populate is:

$(selector).populate(JSON, options)

For example, to populate a very simple form, you might output the following code after the form body:

$('#form').populate({first_name:'Dave',last_name:'Stewart'})

This would fill in the form fields named first_name and last_name with Dave and Stewart respectively.

So what is JSON, and how do I get my data into JSON format in the first place?

JSON stands for JavaScript Object Notation, and it is a very logical, consise and flexible format for describing data (think XML, only lighter).

It can handle the following datatypes:

  • Numbers
  • Strings
  • Object / Arrays
  • Boolean
  • null

For example:

{name:value, array:[value, value, value], object:{name:value}}

To get your data into JSON format, you can either build the string manually, or if you're working in PHP and you've just grabbed some database output for example, you would use a class that parses the data into JSON format, then output that to the page as part of your JavaScript call.

Here's how the code in a typical PHP / HTML page might look:

<?php
    $results = $db->get_results($sql); // get database data
    $json = $JSON->encode($results); // convert to JSON format
?>
<script type="text/javascript">
	$('#form').populate(<?php echo $json; ?>); // jquery populate form
</script>

If you go the class-way, it is important that your data structure has name/value pairs named the same as your form element names, so Populate can associate the array-key names with the form-elements names.

Note: The PHP classes to convert data-structures to JSON are included in the Download section.

What data do I store in the JSON object to update my form?

You should store both the name attribute and the value attribute of the targeted form element.

For text boxes, this is pretty obvious, seeing as that's the only value that can be stored anyway:

{name:'Dave Stewart'}

But for items like radiobuttons, you may be tempted to store an index. Don't! Populate is going to be searching that array for an actual value to match up with.

Say, for example, you have a radiobutton array of 3 colours:

The code for these radiobuttons might look like this:

<input name="color" type="radio" value="red"  /> Red
<input name="color" type="radio" value="green"  /> Green
<input name="color" type="radio" value="blue"  /> Blue 				

So if you wanted to have the second radiobutton checked, you would store the value of that radiobutton (green), and NOT the index (1):

{color:'green'}

I may include support for indices in the future, but for now, it's values.

How does Populate target each type of form element?

Different HTML form elements have different datatypes, and are populated in different ways. This table lists how, and in what format Populate expects the JSON data.

Element What gets populated JSON datatype
Text field, Text area, Label, Hidden Updates the field's text value String value
Radio Buttons Selects a radiobutton index String value
Dropdown, List Selects an item String value
Checkbox (checkbox) Checks or unchecks the box String value
Checkbox array (checkbox[]) Checks or unchecks boxes Array of string values
Multi-list Selects multiple items Array of string values
Button, Submit Updates the button's text String value
Any other element Updates the element's inner text String

 

What's all this about hierarchical forms and PHP naming, then?

JSON is natively hierarchical, and PHP supports a very useful feature which is that any form fields named using square-bracket notation automatically transmit their values to the server hierarchically (not a lot of people know this, for some reason).

For example:

<input type="hidden" name="id" value="1" />
<input type="text" name="contact[first_name]" value="Dave" />
<input type="text" name="contact[last_name]" value="Stewart" />

Would be interpreted natively by PHP as a multi-dimensional array:

Array
(
    [id] => 1
    [contact] => Array
        (
            [first_name] => Dave
            [last_name] => Stewart
        )

)

This makes it very easy to break up large forms into bite-sized chunks, and you can nest your levels as deep as you like - just[keep][adding][new][keys].

And when you want to repopulate the form, you just ensure your JSON is also hierarchical:

{
	id:1, 
	contact:
	{
		first_name:'Dave', 
		last_name:'Stewart'
	}
}

For numeric arrays, just omit the key names from within the square brackets:

<input type="checkbox" name="colors[]" value="red" />
<input type="checkbox" name="colors[]" value="green" />
<input type="checkbox" name="colors[]" value="blue" />

And to re-populate the form, you just just provide an array of values (note how the HTML element name has brackets, but the JSON object doesn't. Populate handles all this for you):

{'colors':['green','blue']}

So, by following naming conventions in your HTML forms, and using hierarchical JSON and Populate, you can:

  • Keep data on both server and client in a hierarchical format
  • Reduce the drudgery of parsing large forms by compartmentalizing your data in sub-arrays

 

Populate options

As with most jQuery plugins, Populate has some options you can set as part of the function call, for example:

$(#'form').populate(json, {resetForm:false, debug:true})

The following table lists those options, what they do, and the defaults.

Option What it does Default
debug If the user has Firebug, print to the console any badly-named elements, and create a global _populate object that contains debugging data false
resetForm Clears the form before populating it true
phpNaming When searching for elements in the form, automatically adds square brackets to any elements that are found that should contain array datatypes, e.g. "colors[]", "colors[]" true
phpIndices Again, when targeting elements that should contain array datatypes, it ensures the name matched by populate contains 0-base indices, e.g. "colors[0]", "colors[1]" false
identifier When targeting non-form elements, specifies the attribute to use for identifying them. Leave blank for "id", or replace with something like "name" or "href" 'id'

 

Populating a form with simple datatypes

Code example

In its simplest format, named JSON objects just mirror the named form fields, so all you need to do to populate a form is to name your JSON objects identically to the fields in your HTML form, and include the values that you want to populate with.

$('#form-simple').populate({
	'name':'Dave Stewart',
	'country':'scotland',
	'contact':'phone'
})

Experiment with the JSON sample below, click "Populate" to see the form update, then submit the form to see the raw variables.

Form controls

JSON

Populating a form with complex datatypes

Code example

Sometimes you will want to send complex datatypes to the server, for example multi-list boxes that hold an array of values, or you might want to combine several values in one set of checkboxes.

For these elements, you make sure the values are held in an array:

$('#form-complex).populate({
	'name':'Dave Stewart',
	'country':['scotland','ireland'],
	'contact':['email','phone']
})

If you look at the source code, note how the complex-type elements have square-brackets at the end of their names. This is ncessary in PHP to force the server to interpet the data from these controls as arrays.

Experiment with the JSON sample below, click "Populate" to see the form update, then submit the form to see the raw variables.

Form controls

JSON

 

Populating a hierarchically-named form with hierarchical JSON data

Code example

When forms get large, it's often preferable to break them up into smaller sections. It makes it easier for the user, and if you name your form elements using PHP naming conventions, it makes it easy for the developer as well!

For the JSON, you just enlose your data objects within other named objects:

$('#form-hierarchical').populate({
	personal:{
		first_name:'Dave',
		last_name:'Stewart',
		country:'england'
		},
	contact:{
		email:'fred@fred-bloggs.com',
		phone:'020 0000 0000',
		method:'email'
		}
})

.

Form controls

Personal
Contact

JSON

 

Populating non-form elements within a form

Code example

Sometimes as part of your form population, you'll want to update areas of text. Populate makes it easy to target the whole form, not just control elements, and update where necessary by changing that element's HTML.

This functionality is currently buggy, and is undergoing review!

Download Highlight here

Download

JavaScript

PHP

Demo files

Feedback

If you have any comments, or wish to report any bugs or unexpected behaviour, please do so using the commenting system on the project's blog page.

I can't promise to answer questions on usage (that's what this help is for!), but I'll do my best to fix bugs.

Cheers,

Dave