Fieldset Class
The Fieldset class is used to create a form and handle its validation in an object oriented way. It uses the Form
and Validation classes. This class itself is only meant to model the fieldset and its fields while the other
two classes do the real work.
Every field in a fieldset is defined by a Fieldset_Field object, which you can access
and manipulate directly using the field() method of the Fieldset.
The resulting form markup is generated when passing the Fieldset instance to a View or by calling build().
forge($name = 'default', $config = array())
The forge method returns a new Fieldset instance. Note: there can only be one instance per $name.
Static |
Yes |
Parameters |
Param |
Default |
Description |
$name |
'default'
|
Identifier for this fieldset |
$config |
array() |
Configuration array |
|
Returns |
\Fieldset Object |
Example |
$article_form = Fieldset::forge('article');
|
When constructing a Fieldset object, you can pass a configuration array which allows you to setup
the object with a custom configuration. The following items are supported:
validation_instance |
Validation object |
null
|
An existing Validation class object you want to use to validate the fieldset. If not given,
a new Validation object will be constructed for this fieldset.
|
form_instance |
Form object |
null
|
An existing Form class object you want to use to construct the fieldset form. If not given,
a new Form object will be constructed for this fieldset.
|
In addition to these fields, you can pass custom form configuration to modify the way the fieldset generates the form.
For valid configuration values, have a look at the form.php configuration file.
instance($instance = null)
Returns a specific instance, or the default instance (is created if necessary).
Static |
Yes |
Parameters |
Param |
Default |
Description |
$instance |
null
|
Identifier of the fieldset instance you want to retrieve |
|
Returns |
\Fieldset Object
or false if the specified instance doesn't exist. |
Example |
$article_form = Fieldset::instance('article');
|
validation()
Gets the Validation instance for the current Fieldset. Creates the Validation instance if it doesn't already exist.
Static |
No |
Returns |
\Validation Object |
Example |
$validation = $article_form->validation();
|
Gets the Form instance for the current Fieldset. Creates the Form instance if it doesn't already exist.
Static |
No |
Returns |
\Form Object |
Example |
$form = $article_form->form();
|
add($name, $label = '', array $attributes = array(), array $rules = array())
Creates a Fieldset_Field instance and adds it to the current Fieldset.
Static |
No |
Parameters |
Param |
Default |
Description |
$name |
required |
HTML name attribute, also used for referencing the field within the Fieldset |
$label |
''
|
Field label |
$attributes |
array()
|
HTML attributes as an associative array |
$rules |
array()
|
Validation rules to be applied to this Field |
|
Returns |
Fieldset_Field instance |
Example |
$title_field = $article_form->add('article_title', 'Title', array('class' => 'pretty_input'));
// Example Radio
$ops = array('male', 'female');
$form->add(
'gender', '',
array('options' => $ops, 'type' => 'radio', 'value' => 'true')
);
// Example Checkbox
$ops = array('male', 'female');
$form->add(
'gender', '',
array('options' => $ops, 'type' => 'checkbox', 'value' => 'true')
);
// Example of an Email input, with validation rules
$form->add(
'email', 'E-mail',
array('type' => 'email', 'class' => 'pretty_input'),
array('required', 'valid_email')
);
// Example of an text input, with array notation for the validation rules
$form->add(
'name', 'Full name',
array('type' => 'name', 'class' => 'pretty_input'),
array(array('required'), array('valid_string', array('alpha-numeric', 'dots', 'spaces')))
);
|
delete($name)
Removed a named Fieldset_Field instance from the Fieldset.
Static |
No |
Parameters |
Param |
Default |
Description |
$name |
required |
name of the field within the Fieldset |
|
Returns |
The current Fieldset instance |
Throws |
RuntimeException, if the field given is not defined |
Example |
$fieldset->delete('article_title');
|
duplicate($name, $newname)
Duplicates a named Fieldset_Field instance from the Fieldset.
Static |
No |
Parameters |
Param |
Default |
Description |
$name |
required |
name of the current field within the Fieldset |
$newname |
required |
name of the duplicated field within the Fieldset |
|
Returns |
The current Fieldset instance |
Throws |
RuntimeException, if the field given is not defined |
Throws |
RuntimeException, if the field given is not defined |
Example |
$fieldset->delete('article_title');
|
add_before($name, $label = '', array $attributes = array(), array $rules = array(), $fieldname = null)
Creates a Fieldset_Field instance and adds it to the current Fieldset, just before an already defined field identified by $fieldname.
Static |
No |
Parameters |
Param |
Default |
Description |
$name |
required |
HTML name attribute, also used for referencing the field within the Fieldset |
$label |
''
|
Field label |
$attributes |
array()
|
HTML attributes as an associative array |
$rules |
array()
|
Validation rules to be applied to this Field |
$fieldname |
null
|
Already defined field to which this field must be prepended |
|
Returns |
Fieldset_Field Object |
Example |
// Radio button field, to be added before the 'location' field.
$ops = array('male', 'female');
$form->add_before('gender', '', array('options' => $ops, 'type' => 'radio', 'value' => 'true'), array(), 'location');
|
add_after($name, $label = '', array $attributes = array(), array $rules = array(), $fieldname = null)
Creates a Fieldset_Field instance and adds it to the current Fieldset, just after an already defined field identified by $fieldname.
Static |
No |
Parameters |
Param |
Default |
Description |
$name |
required |
HTML name attribute, also used for referencing the field within the Fieldset |
$label |
''
|
Field label |
$attributes |
array()
|
HTML attributes as an associative array |
$rules |
array()
|
Validation rules to be applied to this Field |
$fieldname |
null
|
Already defined field to which this field must be appended |
|
Returns |
Fieldset_Field Object |
Example |
// Radio button field, to be added after the 'location' field.
$ops = array('male', 'female');
$form->add_after('gender', '', array('options' => $ops, 'type' => 'radio', 'value' => 'true'), array(), 'location');
|
field($name = null)
Gets one or all Fieldset_Field instances for the current Fieldset.
Static |
No |
Parameters |
Param |
Default |
Description |
$name |
null
|
The name of an existing field in this Fieldset or null to get all fields. |
|
Returns |
Fieldset_Field instance
or an array() of Fieldset_Field instances |
Example |
$fields = $article_form->field();
$title_field = $article_form->field('article_title');
|
add_model($class, $instance = null, $method = 'set_form_fields')
Add a model's fields. The model must have a method set_form_fields() that takes this Fieldset instance and adds fields to it.
Orm\Model have support this build in.
Static |
No |
Parameters |
Param |
Default |
Description |
$class |
required |
Either a full classname (including full namespace) or object instance of the model to get fields from. |
$instance |
null
|
Array or object that has the exactly same named properties to populate the fields. (Takes the field names from the model and fetches the remaining parameters from this array/object. |
$method |
'set_form_fields'
|
The name of the method name to call on the model for field fetching. |
|
Returns |
\Fieldset Object |
Example |
$article_form = Fieldset::forge('article');
$article_form->add_model('Model_Article');
|
set_config($config, $value = null)
Sets a config value on the fieldset.
Static |
No |
Parameters |
Param |
Default |
Description |
$config |
required |
Configuration array. |
$value |
null
|
If specified, sets the item to set from the passed Configuration array. |
|
Returns |
\Fieldset Object |
Example |
$article_form->set_config($config);
// or
$article_form->set_config('key', 'value');
|
get_config($key = null, $default = null)
Get the configuration array or one or more config values by key.
Static |
No |
Parameters |
Param |
Default |
Description |
$key |
null
|
A single key or multiple in an array, empty to fetch all. |
$default |
null
|
A single config value or multiple in an array if $key input is an array to be returned if the items aren't found. |
|
Returns |
array() or mixed |
Example |
$config = $article_form->get_config();
|
get_name()
Get the identifier of the fieldset instance.
Static |
No |
Parameters |
(none) |
Returns |
string |
Example |
$article_form = Fieldset::forge('article');
$name = $article_form->get_name(); // 'article'
|
populate($input, $repopulate = false)
Set initial field values to the given input, optionally set it to repopulate after that as well.
Static |
No |
Parameters |
Param |
Default |
Description |
$input |
required |
An object or associative array of values to assign to their respective Fields,
or a Model instance to take the values from. |
$repopulate |
false |
Use the repopulate() method after initial populating |
|
Returns |
\Fieldset Object |
Example |
$article_form->populate($model);
|
repopulate()
Set all field values to the input send by a form submission (uses the form method attribute
to decide whether to check POST or GET).
Static |
No |
Parameters |
None
|
Returns |
\Fieldset Object |
Example |
$article_form->repopulate();
|
build($action = null)
Alias for $this->form()->build() for this fieldset. Generates the HTML form markup. See Form.
Static |
No |
Parameters |
Param |
Default |
Description |
$action |
null
|
A URL for the action attribute of the form. |
|
Returns |
string HTML markup |
Example |
$this->template->form = $article_form->build(Uri::create('article/submit'));
|
disable($field)
The disable method allows you to disable a field from being build. You can use this if you want to alter the sequence of fields
on the form, or to create more complex layouts without having to build individual fields.
Static |
No |
Parameters |
Param |
Default |
Description |
$field |
required |
The specific field you want to disable. |
|
Returns |
\Fieldset Object |
Throws |
RuntimeException, if the field given is not defined |
Example |
$fieldset->disable('name');
|
The field is not removed from the fieldset, so it will still be validated.
enable($field)
The enable method allows you to re-enable a field that has been disabled before.
Static |
No |
Parameters |
Param |
Default |
Description |
$field |
required |
The specific field you want to enable. |
|
Returns |
\Fieldset Object |
Throws |
RuntimeException, if the field given is not defined |
Example |
$fieldset->enable('name');
|
Alias for $this->validation()->input(). Gets an array of validated input value(s) from either POST data or given input. See Validation.
Static |
No |
Parameters |
Param |
Default |
Description |
$field |
null
|
A specific field for which to get the input. |
|
Returns |
Array of input or string value of specified field |
Example |
$input_values = $article_form->input();
|
validated($field = null)
Alias for $this->validation()->validated(). Gets an array of input value(s) that passed validation. See Validation.
Static |
No |
Parameters |
Param |
Default |
Description |
$field |
null
|
A specific field for which to get the input. |
|
Returns |
Array of input or string value of specified field, or false if the field isn't found |
Example |
$validated_values = $article_form->validated();
|
error($field = null)
Alias for $this->validation()->error(). Gets an array of input value(s) that did not pass validation. See Validation.
Static |
No |
Parameters |
Param |
Default |
Description |
$field |
null
|
A specific field for which to get the input. |
|
Returns |
Array of input or string value of specified field, or false if the field isn't found |
Example |
$errors = $article_form->error();
|
show_errors(Array $config = array())
Alias for $this->validation()->show_errors(). Returns all errors in a list or with set markup from the $config parameter. See Validation.
Static |
No |
Parameters |
Param |
Default |
Description |
$config |
array()
|
Uses keys open_list, close_list, open_error, close_error & no_errors. Overrides the values |
|
Returns |
Array of input or string value of specified field, or false if the field isn't found |
Example |
$all_errors = $article_form->show_errors();
|
Define an embedded fieldset on a related ORM model to create a One-to-Many form.
Static |
No |
Parameters |
Param |
Default |
Description |
$model |
required |
Fully namespaced name of the related model on which the form must be generated |
$relation |
required |
Name of the relation of the parent object that relates to $model |
$parent |
required |
Parent object that is used to generate the main form, and contains the related records to be displayed in the tabular form |
$blanks |
1
|
Number of empty rows to be displayed in the tabular form |
$pagination |
null
|
Pagination object, to make the tabular form paginated |
|
Returns |
Fieldset, for chaining |
Throws |
RuntimeException, if incorrect parameters are passed |
Example |
See below...
|
The tabular form is displayed in a table, controlled by template definitions in the config/form.php
configuration file. You are free to modify these templates, but you should leave the table structure, as the
fieldset class will add the table headers based on the fields present in each row. This will generate invalid HTML
if you remove the table and row definition from the template.
Return the name of the defined tabular form.
Static |
No |
Parameters |
None
|
Returns |
mixed, the name of the form, or false if the fieldset is not a tabular form |
Example |
if ($name = $form->get_tabular_form())
{
echo '$form is a tabular fieldset named', $name;
}
|
The Fieldset class can be used to create forms from ORM models. The following example will build a
form based on the fields specified in $_properties of your model. In the example, $article
is an instance of Model_Article.
echo Fieldset::forge('article')->add_model($article)->populate($article, true)->build();
If you do not wish every property of the model to be on your form, you can set the form type of
those to false
and they will not be generated.
This actually uses the
Observer_Validation behind the scenes, but you do not need to add it as an observer for this to
work.
The Fieldset class can also be used to create forms for an ORM model object and a Many relation. This is done by embedding
a tabular form fieldset into the main form fieldset, specifying the related model and the name of the relation.
By default, the One-to-Many fieldset is displayed in tabular form, controlled by the template in the config/form.php file.
// We're going to create a one-to-many form of an article, identified by $id, and its comments
// get the article and its related comments
$article = Model_Article::find($id, array('related' => array('comments')));
// create the form fieldset for this article using the ORM model's form definition
$form = Fieldset::forge('article')->add_model($article);
/*
* add the tabular form to it to create the one-to-many table.
*
* the data is provided by the relation 'comments' of the $article object, which
* are objects of the class 'Model_Comment'.
*
* you can disable the fieldset tag to avoid embedded fieldsets in your form
*/
$form->add(\Fieldset::forge('tabular')->set_tabular_form('Model_Comment', 'comments', $article)->set_fieldset_tag(false));
This only works for related models that DO NOT have a compound key!
A tabular form generates HTML input tags that use an array with the name of the relation specified, and the primary key value of the
record as its index value. Any blank rows that are added at the bottom of the table will use the relation name, with a '_new' suffix.
This will allow you to update the parent record, and all related records, in one go, and process the new lines separately.
In this example, you'll see input tag names like comments[12][fieldA]
for existing rows (in this case a row with id = 12
,
and comments_new[0][fieldA]
for a field in the first blank line.
// Process the posted one-to-many form
if (\Input::post())
{
// validate the input
$form->validation()->run();
// if validated, save the updates
if ( ! $form->validation()->error())
{
// update the article record, and any comment record changes
$article->from_array($data);
// do we need to delete tabular form records?
foreach ($data['comments'] as $id => $row)
{
if ($id and ! empty($row['_delete']))
{
unset($article->comments[$id]);
}
}
// do we have a new tabular form record data (assuming we've added only one blank line)?
$data = array_filter($data['comments_new'][0]);
$new_errors = false;
if ( ! empty($data))
{
// check for required fields
if (empty($data['fieldA']) or empty($data['fieldB']))
{
$new_errors = true;
// display an error message about missing required fields here...
}
else
{
// create a new related record
$article->comments[] = Model_Comment::forge(array('article_id' => $article->id, 'fieldA' => $data['fieldA'], 'fieldB' => $data['fieldB']));
}
}
// save the updates
if ( ! $new_errors)
{
if ($article->save())
{
// display a save-succesful message here and redirect away
}
else
{
// display an error message, save was not succesful
}
}
}
else
{
// inform the user validation failed
}
}
The layout of the forms generated by the fieldset is controlled by the form.php configuration file.
The following configuration values can be defined:
prep_value |
boolean |
true
|
If true, form values passed to the fieldset will be escaped using Security::htmlentities().
|
auto_id |
boolean |
true
|
If true, the id attribute for form fields will be generated if not assigned to the fields manually.
|
auto_id_prefix |
string |
'form_'
|
When auto_id is true, prefix the generated id attributes with this string.
|
form_method |
string |
'post'
|
Type of form action to generate. Can be 'get' or 'post'.
|
form_template |
string |
'\n\t\t{open} \n\t\t<table>\n{fields}\n\t\t</table> \n\t\t{close}\n'
|
String containing the placeholders for opening- and closing the form, and for the list of input fields.
|
field_template |
string |
'\t\t<tr> \n\t\t\t<td class=\"{error_class}\"> {label}{required}</td> \n\t\t\t<td class=\"{error_class}\">{field} <span>{description}</span> {error_msg} </td>\n\t\t</tr>\n'
|
String containing the placeholders for generating a single input field.
|
multi_field_template |
string |
'\t\t<tr> \n\t\t\t<td class=\"{error_class}\"> {group_label}{required}</td> \n\t\t\t<td class=\"{error_class}\">{fields} \n\t\t\t\t{field} {label} \n{fields}<span>{description}</span> \t\t\t{error_msg}\n\t\t\t</td>\n\t\t</tr>\n'
|
String containing the placeholders for generating a single input field with multiple inputs, like a group of radio buttons or checkboxes.
|
error_template |
string |
'<span>{error_msg}</span>'
|
String containing the placeholders for generating input error messages.
|
group_label |
string |
'<span>{label}</span>'
|
String containing the placeholders for generating a label for multi field inputs.
|
required_mark |
string |
'*'
|
String containing the HTML to mark input fields as required.
|
inline_errors |
boolean |
false
|
If true, validation error messages will be displayed inline in the form.
|
error_class |
string |
null
|
CSS class name to apply to error messages.
|
label_class |
string |
null
|
CSS class name to apply to field labels.
|
tabular_form_template |
string |
'<table>{fields}</table>\n'
|
template for the complete tabular form with all its rows.
|
tabular_field_template |
string |
'{field}'
|
Template for embedding a child fieldset in a tabular form.
|
tabular_row_template |
string |
'<tr>{fields}</tr>\n'
|
Template for generating a single row in a tabular form.
|
tabular_row_field_template |
string |
'\t\t\t<td>{label}{required} {field} {error_msg}</td>\n'
|
Template for generating a single field in a row of a tabular form.
|
tabular_delete_label |
string |
'Delete?'
|
Column header for the row delete checkbox.
|
The following macro's can be used in a form template.
{open} |
Form open tag, generated by Form::open(); |
{close} |
Form close tag, generated by Form::open(); |
{fields} |
The block of HTML containing all generated input fields. |
{label} |
Input field label, generated by Form::label(); |
{required} |
String indicating the input field is required. |
{error_class} |
Configured class to be applied to error messages. |
{field} |
Generated HTML for the individual input field. |
{description} |
String the field description or a help text to be displayed. |
{error_msg} |
String containing the formatted error message as returned by validation. |
{group_label} |
Input field label for grouped input fields, generated by Form::label(); |
Changing the attributes of the form() instance in the fieldset can be done in two ways. You can either provide your options in the forge() method's attributes array, or modify the form instance directly.
// Use the form_attributes option in the attributes of the Fieldset object
$fieldset = Fieldset::forge('article', array(
'form_attributes' => array(
'id' => 'edit_article_form',
'name' => 'edit_article'
)
)
);
// Modify the form instance directly
$fieldset->form()->set_attribute('id', 'edit_article_form');
More examples to be written.