当前位置: 首页 > 文档资料 > FuelPHP 中文文档 >

Fieldset - 类別

优质
小牛编辑
116浏览
2023-12-01

Fieldset 类别是用来以一个物件导向的方式来建立一个表单并处理它的验证。 它使用 Form 和 Validation 类别。此类别本身只意味着栏位集及其栏位的模型, 而其他两个类别做真正的事。

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

表单标记的结果是在传递 Fieldset 实例到一个检视或透过呼叫 build() 时产生。

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

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

静态
参数
参数预设描述
$name
'default'
给此 Fieldset 的识别符
$configarray()配置阵列
回传\Fieldset 物件
範例
$article_form = Fieldset::forge('article');

当建构一个 Fieldset 物件时,你可以传递一个允许你用自订配置来设置物件的配置阵列。 支援以下项目:

参数类型预设描述
validation_instanceValidation 物件
null
你想用来验证该 Fieldset 的现有 Validation 类别物件。如果没给, 一个新的 Validation 物件会为此 Fieldset 被建构。
form_instanceForm 物件
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.
$repopulatefalseUse 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');
	

更多範例待编写。