DataMapper ORM


HTML Form Generation Methods (htmlform)

No Longer Supported

As of Datamapper ORM 1.7, this extension is not supported. It is almost as complicated as Datamapper ORM itself, and I no longer have the time to maintain it. It is fully functional, but use at your own risk.

You may be able to find support on the CodeIgniter forums, but I am not planning on updating this extension anymore. Feel free to modify this extension directly, and please change the templates to suit your needs.

To enable these methods, add 'htmlform' to DataMapper's config, under 'extensions'.

Uses properties from a DataMapper object to quickly generate forms. This method is highly customizable, both in a broad sense, and on a field-by-field basis. When combined with the Associative Array Conversion Methods, this extension can make creating simple content mangement tools very easy.

Why doesn't this extension use the CodeIgniter Form Helper?

The simple reason is that there is a lot of information available when the input methods are able to look at the DataMapper object directly. Using those methods would have required yet another libary be loaded, and wouldn't have provided much benefit.

Also, I don't think they really do that much, other than output some basic HTML. This extension provides the means to output an entire, ready-to-use HTML form with very little customization.

Load-Time Options

Set these when loading the extension, to change the default behavior.

Name Type Description Default
form_template View Override the default template for the overall form structure. 'dmz_htmlform/form'
row_template View Override the default template for the row structure. 'dmz_htmlform/row'
section_template View Override the default template for form sections. 'dmz_htmlform/section'

 

Getting Started

HTML Form was designed to be highly flexible, while still allowing the simplest cases to require very little coding.

HTML Form Uses the Validation Array

HTML Form can use information already stored in the validation array to significantly automate form generation. The following elements are used as described. Some of these elements are not defined for standard DataMapper usage. All can be overridden on a per-form and per-field basis.

Name Type Description Default
label String The label is used to provide a label for the field. $field
type* String The type is used to determine what type of field is being edited.
For example, 'text', 'password', or 'dropdown'. See below for the built-in types.
'text'
values* Array Used to provide a set of possible keys and values for multiple-choice fields, such as dropdowns, radio buttons, and checkbox lists. NULL
rules Array Some of the rules can affect the rendering of the input field.
For example, 'required' will add a 'required' class to the row, while 'max_length' might be used to limit the size of a text field.
Empty Array

* Not a standard DataMapper validation field.

Example Application

A complete example can be found in the examples section.

For the most simple forms, all that is need is:

  1. Ensure that every field and related field has a label.
  2. Add type to all non-single line text fields. Relationship fields will automatically be generated as a dropdown or checkbox list.
  3. Create an array of field names to edit, in the order you want them to appear. Don't forget id if you are editing an item!
  4. Pass this array into $object->render_form, along with the submit url if it is not the current url.
  5. Echo the result of the method out.

That's all that is needed to render out a complete form with inputs for text, textareas, even single and multiple relationships! The form will also include a block of errors if any occurred while saving.

Note: If you are outputting related fields, you need to implement __toString on your related classes. The result of __toString is used to determine the name to show for dropdowns, checkboxes, and radio buttons.

Relationship fields can only be used with checkbox, radio, or dropdown input types.

Continue reading on for more details of how to enhance this output.

 

Methods

All of the power of this class can be accessed through these three methods.

render_form($fields, $url, $options, $template, $row_template)

Takes a collection of fields, text, and custom inputs and converts them into a submittable form.

Fields Array

All of the work for the form is specified by the $fields array. Each item in the fields can be specified in one of several ways:

There is a lot of power in these options. Many examples are shown below.

Each of the {options array}s can accept any of these standard options:

Name Type Description Default
label String The label is used on the row template to provide a label for the field. See Getting Started
type String Override the default type for the input field. Varies
value Mixed Override the value for fields and related fields. Set the value for custom fields. See Getting Started
default_value Mixed Set the initial value for custom fields. Ignored (and passed to the renderer) for object-based fields. NULL
list Array A set of value/label pairs to be used for multiple-item input fields (dropdown, checkbox, radio).
This can also be a DataMapper object. In this case, $all will be used to create the list.
The list is automatically generated for related objects if you don't specify one. See below for details.
Based on the related field, or
validation['values']
input_separator String Override the default separator used in checkboxes, radio sets, and multiple-inputs. '<br/>' on checkboxes
' ' on multiple-inputs
template View Override the default row (or section) template for just this row (or section). 'dmz_htmlform/row' or
'dmz_htmlform/section'
row_options Array Options passed to the render_row method. This is only used if multiple fields are rendered in one row.
Also acceptable: any options that the render_row method accepts.

All other items in the {options array} are passed directly to the render_row method.


Default Form Template Options

Example Application

The login view contains an example of these options.

ZIP/examples/application/views/login.php

The default form template can take these options. If you customize the template, you can accept any options you want.

Name Type Description Default
save_button String The label to use on the save button. Save
reset_button Mixed If TRUE, show a reset button labled 'Reset'; If not FALSE, use that as the label for a reset button. FALSE

 

render_row($field, $type, $options, $row_template)

Takes a field (or set of options) and converts it into an HTML form input widget, wrapped in a template containing the field label and more. This method isn't called directly very often; instead use render_form.

It is this method that determines whether to render rows with input fields, section headers, or output the content directly.

Default Row Template Options

The default row template can take these options. If you customize the template, you can accept any options you want. ($id is the id of the field.)

Name Type Description Default
label String The label to show for the input(s). ''
row_id String The id of the row. row_$id
label_for String The id of the field, so clicking the label focuses that field.. $id
row_class String The base class for the row. The class will automatically include required and error as applicable, even if you provide one. ''

 

render_field($field, $type, $options)

Takes a field (or set of options) and converts it into an HTML form input widget. This function is the meat of the automation. The method outputs different information based on whether the field is a $has_one or $has_many relationship, a DataMapper field, or none of the above.

Common Input Field Options

These are common options for input fields. Anything not explicitly defined here is output directly to the html as $name="$value".

Name Type Description Default
value Mixed Override the initial value for fields and related fields. Set the initial value for custom fields. See Getting Started
default_value Mixed Set the initial value for custom fields. Ignored (and passed to the renderer) for object-based fields. NULL
list Array A set of value/label pairs to be used for multiple-item input fields (dropdown, checkbox, radio).
This can also be a DataMapper object. In this case, $all will be used to create the list.
The list is automatically generated for related objects if you don't specify one. See below for details.
Based on the related field, or
validation['values']
id String HTML id attribute. $field
class String The base HTML class attribute. ''
size Integer The size of a text field or dropdown box. 30 for text, or
min(8, count($list))
maxlength Integer The maximum accepted length of a text field. validation['rules']['max_length']

Related Lists

If you specify a related field, and do not provide a list of items, this method will attempt to automatically generate a list of items. It does this by loading every item of the related class.

If you decide to use the built-in list generator, you probably want to implement default order by.

If you decide that you do not want every item listed, then there are two options:

Custom Method Example

class User extends DataMapper {

    // ...

    function get_htmlform_list($object, $field)
    {
        // Only return enabled users
        $this->where('disabled', FALSE)->get();
    }
}

 

Types

Different types of input help shape what the user is allowed to submit. You can use one of the built-in types, or create your own type renderers.

Built-In Types

All of the built-in functions will update based on the validation rules. They also will accept almost any key/value pair in the options array, and output them as HTML.

For the examples below:

Single-Value Types

These input types only accept a single value, and the user can enter input as text.

Name Description Sample Output
hidden A special input used for hidden fields. It is never rendered in a row, even within forms. <input type="hidden" id="$id" name="$id" value="$value" />
text The default type. A single-line text box. max_length translates to maxlength, and if it is less than 30, it will also be used to limit the size of the box. <input type="text" id="$id" name="$id" value="$value" />
password A password field that works similar to text, except the value is never returned by default. Set send_value to TRUE to force the value to be sent back to the client. <input type="password" id="$id" name="$id" />
textarea A larger, multi-line text input field. <textarea id="$id" name="$id">$value</textarea>
checkbox A single checkbox. If rendered in a row, the label is rendered on the label. Otherwise, it is rendered beside the checkbox. The value of the field is assumed to be TRUE or FALSE. <input type="checkbox" id="$id" name="$id" value="$id" checked="{$value}" />
file File upload field. The initial value parameter is ignored by this input. <input type="file" id="$id" name="$id" />

Limited-Selection Single-Value Types

These input types only accept a single value. The options the user can select are limited by the values validation property, the list property, or auto-generated for related items.

You will need to implement the __toString PHP method on related models, to get a label for these.

Name Description Sample Output
dropdown A selection box that allows the user to select one of many options. <select id="$id" name="$id" >
    <option value="$listkey1">$listvalue1</option>
    <option value="$listkey2" selected="selected">$listvalue2</option>
</select>
radio Renders a list of radio items a user can choose between. <input type="radio" id="$id_$listkey1" name="$id" value="$listkey1" />
    <label for="$id_$listkey1">$listvalue1</label><br/>
<input type="radio" id="$id_$listkey2" name="$id" value="$listkey2" checked="checked" />
    <label for="$id_$listkey2">$listvalue2</label>

Limited-Selection Multiple-Value Types

These input types accept multiple values. The options the user can select are limited by the values validation property, the list property, or auto-generated for related items.

You will need to implement the __toString PHP method on related models, to get a label for these.

Name Description Sample Output
dropdown A selection box that allows the user to select one or more of many options. <select id="$id" name="$id" >
    <option value="$listkey1" selected="selected">$listvalue1</option>
    <option value="$listkey2">$listvalue2</option>
    <option value="$listkey3" selected="selected">$listvalue3</option>
</select>
checkbox Renders a list of checkbox items a user can choose between. <input type="checkbox" id="$id_$listkey1" name="$id" value="$listkey1" />
    <label for="$id_$listkey1">$listvalue1</label><br/>
<input type="checkbox" id="$id_$listkey2" name="$id" value="$listkey2" checked="checked" />
    <label for="$id_$listkey2">$listvalue2</label>

Custom Types

HTML Form includes several types (listed below). You can also add any type by simply creating a helper function to render it.

The helper function must be named input_{$type}, and must take these arguments:

Example

// Render a JavaScript Calendar
function input_calendar($object, $field, $value, $options)
{
    return "<input type=\"text\" id=\"$field\" name=\"$field\" value=\"$value\" onFocus=\"showCalendar(this);\" onBlur=\"hideCalendar(this);\" />";
}

Then simply set the type of any object to calendar to use this input type.

 

Custom Templates

It is easy to customize the templates in use. A template is simply a view, and all $options are passed into it directly as variables. There are three default templates:

You can easily override or specify different templates in several ways:

 

Code Examples

For all examples, assume $u is a User.

Basic Form

This outputs a complete, ready-to-use HTML form including grouping the fields, and errors messages.

echo $u->render_form(array(
        'id',
        // Section header
        'Contact Information' => 'section',
        'name',
        'email',
        'phone',

        // Section header
        'Login Information' => 'section',
        'username',
        'password',
        'confirm_password',

        // Since user can only have one group, this will render out as a standard drop-down of all Groups.
        'group'
    ),
    'users/save' // form submit URL
);

Overriding the Default Type

A simple change converts the name into a multi-line textarea.

echo $u->render_form(array(
        'id',
        // Section header
        'Contact Information' => 'section',
        'name' => 'textarea',
        'email',
        'phone',

        // Section header
        'Login Information' => 'section',
        'username',
        'password',
        'confirm_password',

        'group'
    ),
    'users/save' // form submit URL
);

Customizing the Output

Changing the label, field-level styling, changing options on a dropdown, and custom button labels are shown below.

$g = new Group();
// Don't include groups that only admins can see
$g->where('admin_only', FALSE)->get();

echo $u->render_form(array(
        'id',
        // Section header
        'Contact Information' => 'section',

        // Override label and size, add custom styling
        'name' => array(
            'label' => 'Your Name',
            'size' => '40',
            'style' => 'color: Green; font-weight: bold;'
        ),
        'email',
        'phone',

        // Section header
        'Login Information' => 'section',
        'username',
        'password',
        'confirm_password',

        // We want to limit the groups visible
        'group' => array(
            'list' => $g
        )
    ),
    'users/save', // form submit URL
    // Customize the form
    array('save_button' => 'Save this form NOW', 'reset_button' => 'Clear')
);

Multi-Field Row

Use this format to place more than one field on a line.

echo $u->render_form(array(
        'id',
        // output:
        // Name: [firstname] [middlename] [lastname]
        array(
            'row_options' => array(
                'label' => 'Name' // the row's Label
            ),
            'firstname',
            'middlename',
            'lastname'
        ),
        'email',
        // ...