Fieldset 类別

Fieldset 类別是用來以一个物件導向的方式來建立一个表单并处理它的驗證。 它使用 Form 和 Validation 类別。此类別本身只意味著欄位集及其欄位的模型, 而其他兩个类別做真正的事。

每个在欄位集中的欄位是透過一个 Fieldset_Field 物件來定義, 你可以直接使用 Fieldset 的 field() 方法來存取及操作。

表单标記的結果是在傳遞 Fieldset 實例到一个檢視或透過呼叫 build() 時產生。

forge($name = 'default', $config = array())

forge 方法回傳一个新的 Fieldset 實例。注意:每个 $name 只能有一个實例。

靜態
參数
參数 預設 描述
$name
'default'
給此 Fieldset 的識別符
$config array() 配置陣列
回傳 \Fieldset 物件
範例
$article_form = Fieldset::forge('article');

當建構一个 Fieldset 物件時,你可以傳遞一个允許你用自訂配置來設置物件的配置陣列。 支援以下項目:

參数 类型 預設 描述
validation_instance Validation 物件
null
你想用來驗證該 Fieldset 的现有 Validation 类別物件。如果沒給, 一个新的 Validation 物件会为此 Fieldset 被建構。
form_instance Form 物件
null
你想用來建構該 Fieldset 表单的现有 Form 类別物件。如果沒給, 一个新的 Form 物件会为此 Fieldset 被建構。

除了这些欄位,你可以傳遞自訂表单配置來修改 Fieldset 產生表单的方式。 對於有效的配置值,看看 form.php 配置档案。

instance($instance = null)

回傳一个指定的實例,或預設實例(如果必要時建立)。

靜態
參数
參数 預設 描述
$instance
null
你想檢索 Fieldset 實例的識別符
回傳 \Fieldset 物件
false 如果指定的實例不存在。
範例
$article_form = Fieldset::instance('article');

validation()

取得 Validation 實例給目前的 Fieldset。建立該 Validation 實例如果它還不存在。

靜態
回傳 \Validation 物件
範例
$validation = $article_form->validation();

form()

取得 Form 實例給目前的 Fieldset。建立該 Form 實例如果它還不存在。

靜態
回傳 \Form 物件
範例
$form = $article_form->form();

add($name, $label = '', array $attributes = array(), array $rules = array())

建立一个 Fieldset_Field 實例并添加到目前的 Fieldset。

靜態
參数
參数 預設 描述
$name 必要 HTML name 屬性,也用於參照 Fieldset 中的欄位
$label
''
欄位标籤
$attributes
array()
HTML 屬性做为一个關聯陣列
$rules
array()
要被應用在此欄位的驗證規則
回傳 Fieldset_Field 實例
範例
$title_field = $article_form->add('article_title', 'Title', array('class' => 'pretty_input'));

// Radio 範例
$ops = array('male', 'female');
$form->add(
	'gender', '',
	array('options' => $ops, 'type' => 'radio', 'value' => 'true')
);

// Checkbox 範例
$ops = array('male', 'female');
$form->add(
	'gender', '',
	array('options' => $ops, 'type' => 'checkbox', 'value' => 'true')
);

// Email input 範例,使用驗證規則
$form->add(
	'email', 'E-mail',
	array('type' => 'email', 'class' => 'pretty_input'),
	array('required', 'valid_email')
);

// text input 範例,使用陣列表示的驗證規則
$form->add(
	'name', 'Full name',
	array('type' => 'name', 'class' => 'pretty_input'),
	array(array('required'), array('valid_string', array('alpha-numeric', 'dots', 'spaces')))
);

delete($name)

從 Fieldset 移除一个具名的 Fieldset_Field 實例。

靜態
參数
參数 預設 描述
$name 必要 Fieldset 內的欄位名稱
回傳 目前的 Fieldset 實例
範例
$fieldset->delete('article_title');

add_before($name, $label = '', array $attributes = array(), array $rules = array(), $fieldname = null)

建立一个 Fieldset_Field 實例并添加它到目前的 Fieldset,就在已定義的透過 $fieldname 識別的欄位之前。

靜態
參数
參数 預設 描述
$name 必要 HTML name 屬性,也用於參照 Fieldset 中的欄位
$label
''
欄位标籤
$attributes
array()
HTML 屬性做为一个關聯陣列
$rules
array()
要被應用在此欄位的驗證規則
$fieldname
null
應該被附加在此欄位前的已定義欄位
回傳 Fieldset_Field 物件
範例
// Radio 按鈕欄位,被添加在 'location' 欄位之前。
$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)

建立一个 Fieldset_Field 實例并添加它到目前的 Fieldset,就在已定義的透過 $fieldname 識別的欄位之後。

靜態
參数
參数 預設 描述
$name 必要 HTML name 屬性,也用於參照 Fieldset 中的欄位
$label
''
欄位标籤
$attributes
array()
HTML 屬性做为一个關聯陣列
$rules
array()
要被應用在此欄位的驗證規則
$fieldname
null
應該被附加在此欄位後的已定義欄位
回傳 Fieldset_Field 物件
範例
// Radio 按鈕欄位,被添加在 'location' 欄位之後。
$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.

靜態
參数
參数 預設 描述
$name
null
The name of an existing field in this Fieldset or null to get all fields.
回傳 Fieldset_Field 實例
或一个 Fieldset_Field 實例的 array()
範例
$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.

靜態
參数
參数 預設 描述
$class 必要 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.
回傳 \Fieldset 物件
範例
$article_form = Fieldset::forge('article');
$article_form->add_model('Model_Article');

set_config($config, $value = null)

在 Fieldset 設定一个配置值。

靜態
參数
參数 預設 描述
$config 必要 配置陣列。
$value
null
如果指定,從傳遞的配置陣列來設定該項目。
回傳 \Fieldset 物件
範例
$article_form->set_config($config);

// 或

$article_form->set_config('key', 'value');

get_config($key = null, $default = null)

透過鍵取得配置陣列的一个或更多配置值。

靜態
參数
參数 預設 描述
$key
null
在一个陣列中的单一或多个鍵,空值來取回全部。
$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.
回傳 array() 或混合
範例
$config = $article_form->get_config();

get_name()

取得 Fieldset 實例識別。

靜態
參数 (無)
回傳 字串
範例
$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.

靜態
參数
參数 預設 描述
$input 必要 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
回傳 \Fieldset 物件
範例
$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).

靜態
參数
回傳 \Fieldset 物件
範例
$article_form->repopulate();

build($action = null)

Alias for $this->form()->build() for this fieldset. Generates the HTML form markup. See Form.

靜態
參数
參数 預設 描述
$action
null
A URL for the action attribute of the form.
回傳 HTML 标記字串
範例
$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.

靜態
參数
參数 預設 描述
$field 必要 你想要停用的指定欄位。
回傳 \Fieldset 物件
拋出 RuntimeException,如果所給欄位沒定義
範例
$fieldset->disable('name');

The field is not removed from the fieldset, so it will still be validated.

enable($field)

enable 方法能让你重新啟用之前已经被停用的欄位。

靜態
參数
參数 預設 描述
$field 必要 你想要啟用的指定欄位。
回傳 \Fieldset 物件
拋出 RuntimeException,如果所給欄位沒定義
範例
$fieldset->enable('name');

input($field = null)

$this->validation()->input() 的別名。取得一个驗證過的來自 POST 或所給輸入的輸入值陣列。詳見 Validation

靜態
參数
參数 預設 描述
$field
null
要取得輸入的指定欄位。
回傳 輸入的陣列或指定欄位的字串值
範例
$input_values = $article_form->input();

validated($field = null)

$this->validation()->validated() 的別名。取得一个通過驗證的輸入值陣列。詳見 Validation

靜態
參数
參数 預設 描述
$field
null
要取得輸入的指定欄位。
回傳 輸入的陣列或指定欄位的字串值,或 false 如果欄位找不到
範例
$validated_values = $article_form->validated();

error($field = null)

$this->validation()->error() 的別名。取得一个沒通過驗證的輸入值陣列。詳見 Validation

靜態
參数
參数 預設 描述
$field
null
要取得輸入的指定欄位。
回傳 輸入的陣列或指定欄位的字串值,或 false 如果欄位找不到
範例
$errors = $article_form->error();

show_errors(Array $config = array())

$this->validation()->show_errors() 的別名。回傳列表中的所有错误,或帶來自 $config 參数的設定标記。詳見 Validation

靜態
參数
參数 預設 描述
$config
array()
使用 open_list、close_list、open_error、close_error & no_errors 鍵。覆寫其值
回傳 輸入的陣列或指定欄位的字串值,或 false 如果欄位找不到
範例
$all_errors = $article_form->show_errors();

set_tabular_form($model, $relation, $parent, $blanks = 1)

Define an embedded fieldset on a related ORM model to create a One-to-Many form.

靜態
參数
參数 預設 描述
$model 必要 Fully namespaced name of the related model on which the form must be generated
$relation 必要 Name of the relation of the parent object that relates to $model
$parent 必要 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
回傳 Fieldset,鍊結用
拋出 RuntimeException,如果不正確的參数被傳遞
範例 以下……

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.

get_tabular_form()

回傳定義的表格式表单的名稱。

靜態
參数
回傳 混合,表单名稱,或 false 如果 Fieldset 不是一个表格式表单
範例
if ($name = $form->get_tabular_form())
{
	echo '$form is a tabular fieldset named', $name;
}

使用 ORM 模型建立表单

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.

Creating One-to-Many forms with ORM Models

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 it's comments

// get the article and it's 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));
				

这只適用於沒有複合鍵的關聯模型!

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 it's 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.

以下配置值可以被定義:

參数 类型 預設 描述
prep_value 布林
true
If true, form values passed to the fieldset will be escaped using Security::htmlentities().
auto_id 布林
true
If true, the id attribute for form fields will be generated if not assigned to the fields manually.
auto_id_prefix 字串
'form_'
When auto_id is true, prefix the generated id attributes with this string.
form_method 字串
'post'
Type of form action to generate. Can be 'get' or 'post'.
form_template 字串
'\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 字串
'\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 字串
'\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 字串
'<span>{error_msg}</span>'
String containing the placeholders for generating input error messages.
group_label 字串
'<span>{label}</span>'
String containing the placeholders for generating a label for multi field inputs.
required_mark 字串
'*'
String containing the HTML to mark input fields as required.
inline_errors 布林
false
If true, validation error messages will be displayed inline in the form.
error_class 字串
null
CSS class name to apply to error messages.
label_class 字串
null
CSS class name to apply to field labels.
tabular_form_template 字串
'<table>{fields}</table>\n'
template for the complete tabular form with all it's rows.
tabular_field_template 字串
'{field}'
Template for embedding a child fieldset in a tabular form.
tabular_row_template 字串
'<tr>{fields}</tr>\n'
Template for generating a single row in a tabular form.
tabular_row_field_template 字串
'\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 字串
'Delete?'
Column header for the row delete checkbox.

表单屬性巨集

以下巨集可被用在表单樣板。

參数 描述
{open} 表单開始标籤,由 Form::open(); 產生
{close} 表单結束标籤,由 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();

修改表单屬性

變更在 Fieldset 中 form() 實例的屬性可用兩種方式辦到。你可以在 forge() 方法的屬性陣列中提供你的選項,或直接修改 Form 實例。

// 在 Fieldset 物件的屬性中使用 form_attributes 選項
$fieldset = Fieldset::forge('article', array(
	'form_attributes' => array(
		'id' => 'edit_article_form',
		'name' => 'edit_article'
		)
	)
);

// 直接修改表单實例
$fieldset->form()->set_attribute('id', 'edit_article_form');
				

更多範例待编寫。