Cakephp FormHelper表单输入

本文详细介绍了CakePHP框架中的FormHelper组件,包括快速创建表单、表单元素的生成、自定义表单样式和行为,以及如何处理表单提交后的逻辑。重点覆盖了表单的创建、输入元素的配置、结束表单的方法、特定类型输入的使用,以及高级选项的设置,旨在帮助开发者高效地构建动态交互式的表单。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class FormHelper(View $view, array $settings = array())

FormHelper注重于快速创建表单,完成表单创建大部分工作。FormHelper较灵活,可以完成几乎所有你想要的表单格式创建,只需通过自带的简单方法。

1. 创建Form

首先,创建表单时,调用FormHelper第一个方法create(),输出一个开放的表单标记:

FormHelper::create(string $model = null, array $options = array()),注意事项:

l 所有的参数都是可选的,如果调用时无参数输入,表单默认提交到当前Controller和当前action

l 表单默认创建提交格式为“POST”。

l 表单元素依旧存在Dom id值,id内容包括当前Controlleraction值。

假如在UserController界面中调用create()函数,则在界面中导入如下内容:

<form id="UserAddForm" method="post" action="/users/add">

注:也可以设置model = false。这将会表单数据提交到数组:$this->request->data(而不是$this->request->data['Model'])。这种方便的简写形式,可能无法代表数据库中的任何字段。

通过设置Create()参数,可以得到各式各样的表单格式。首先,通过设置$model参数,及创建了一个Form区。所有的字段被假定为属于该Model(除非另行规定)。如果不设定Model,默认为与当前Controller相关的model

// /recipes/add中输入

echo $this->Form->create('Recipe');

则,输入HTML内容为:

<form id="RecipeAddForm" method="post" action="/recipes/add">

上述代码标明,FormPost方式提交数据到RecipeControlleradd action。当然,我们也可以以相同的方式创建用于编辑的FormFormHelper使用$this->request->data属性可判断是否创建了一个addedit表单。如果$this->request->data包含以当前Model命名的数组或数据主键非空值,FormHelper将会创建一个编辑表单。比如,浏览http://localhost/recipes/edit/5, 得到:

// Controller/RecipesController.php:

public function edit($id = null) {

    if (empty($this->request->data)) {

        $this->request->data = $this->Recipe->findById($id);

    } else {

        // Save logic goes here

    }

}

 

// View/Recipes/edit.ctp:

// Since $this->request->data['Recipe']['id'] = 5,

// we will get an edit form

<?php echo $this->Form->create('Recipe'); ?>

输出HTML内容:

<form id="RecipeEditForm" method="post" action="/recipes/edit/5">

<input type="hidden" name="_method" value="PUT" />

由于这是一个编辑表单,一个隐藏的输入字段覆盖默认的HTTP方法。

当创建的plugins中Model时,要使用正确的插件语法。比如:

echo $this->Form->create('ContactManager.Contact');

1.1 Options参数

$ options数组包含多个不同的键 影响生成的form格式。

注:Form默认的提交Url是当前Url路劲,在2.0版本以后,可通过设置$options['url']参数进行自定义更改。

$options参数有很多,下面将一一介绍。

l $options['type']:设置Form提交方式。有效值包括“postgetfileput’ and delete”。

echo $this->Form->create('User'array('type' => 'get'));

输出HTML内容:

<form id="UserAddForm" method="get" action="/users/add">

指定type = file’时,表单提交方式为post,在表单标签中包含属性enctype="multipart/form-data",用于文件的提交,确保文件上传成功。

echo $this->Form->create('User'array('type' => 'file'));

输出HTML内容:

<form id="UserAddForm" enctype="multipart/form-data"

   method="post" action="/users/add">

当type=’put’或‘delete’时,表格格式与post格式相同,只是在提交的时候HTTP请求方法将“PUT”或“DELETE”,使得CakePHP实现模仿正确的REST支持的Web浏览器。

l $options['action']:From提交之后指向当前Controlleraction路径。

echo $this->Form->create('User', array('action' => 'login'));

输出HTML内容:

<form id="UserLoginForm" method="post" action="/users/login">

l $options['url']:当需要设置Form提交后不指向当前Controlleraction,就需要设置该参数来实现。比如:、

echo $this->Form->create(null, array(

    'url' => array('controller' => 'recipes', 'action' => 'add')

));

 

输出HTML内容(指向RecipeController下的add action:

 

<form method="post" action="/recipes/add">

 

或者指向远程域:

echo $this->Form->create(nullarray(

    'url' => 'http://www.google.com/search',

    'type' => 'get'

));

输出HTML内容(指向远程域):

<form method="get" action="http://www.google.com/search">

更多url格式设置请参考HtmlHelper::url内容。

l $options['default']:当设置此参数为false时,点击表单提交按钮,不提交表单到Controller。而是通过AJAX方式提交数据。

l $options['inputDefaults']:设置表单输入属性。

echo $this->Form->create('User'array(

    'inputDefaults' => array(

        'label' => false,

        'div' => false

    )

));

在'inputDefaults' 设置之后的所有input将继承其为默认属性。我们也可以通过在input()设置option参数来覆盖默认设置:

echo $this->Form->input('password'); // div = false; label = false ;No div, no label

// has a label element

echo $this->Form->input(

    'username',

    array('label' => 'Username')  //override

);

 

2. Form结尾

方法:FormHelper::end($options = null, $secureAttributes = array())

<?php echo $this->Form->create(); ?>

<!-- Form elements go here -->

<?php echo $this->Form->end(); ?>

表单通过end()方法结束,通常end()只输出一个结束标签,但是,通过设置end()中参数,end()可以插入SecurityComponent要求的隐藏表单元素。

如果一个字符串作为end()的第一个参数,则输出提交按钮,值为该字符串,并包含Form结束标签,如下

<?php echo $this->Form->end('Finish'); ?>

输出HTML内容:

<div class="submit">

    <input type="submit" value="Finish" />

</div>

</form>

我们也可以传递字符串到end()参数:

$options = array(

    'label' => 'Update',

    'div' => array(

        'class' => 'glass-pill',

    )

);

echo $this->Form->end($options);

输出HTML内容:

<div class="glass-pill"><input type="submit" value="Update" name="Update">

</div>

注:如果在表单应用中使用SecurityComponent,表单必须以end()结尾。

3. 创建表单元素

有多种方法创建表单元素,先从input()开始介绍。方法自动检测输入field,创建field对应表单元素。

3.1 方法input()

方法:FormHelper::input(string $fieldName, array $options = array())

通过设置fieldName参数,设置如下表单元素和属性:

l Div

l Label属性

l Input 属性

l Error 属性(如果适用)

Input输入类型需通过设置列的输入类型来实现:

 

输入类型

Form输入域类型

string (char, varchar, etc.)

text

boolean, tinyint(1)

checkbox

text

textarea

text, with name of password, passwd, or psword

password

text, with name of email

email

text, with name of tel, telephone, or phone

tel

date

day, month, and year selects

datetime, timestamp

day, month, year, hour, minute, and meridian selects

time

hour, minute, and meridian selects

binary

file

 

$options参数允许自定义如何input()属性。Div包含所添加的input元素,自动导入(除设置allowEmpty => true)Model中由required设置的输入参数属性,并直接关联到create()

2.3版本以后,HTML5required设置增加到input()的输入有效性验证。可以在$option中设置并覆盖Model中的设置。如果要跳过浏览器验证输入合法性,需通过FormHelper::submit() $option设置'formnovalidate' => true或在Create() $option中设置'novalidate' => true实现。

比如,用户模型包括'username'(数据类型为varchar)字段,'password'(VARCHAR),'approved'(日期时间)和'quote'(文本)。使用FromHelperinput()为字段创建合适的输入:

echo $this->Form->create();

echo $this->Form->input('username');   //text

echo $this->Form->input('password');   //password

echo $this->Form->input('approved');   //day, month, year, hour, minute,

                                       //meridian

echo $this->Form->input('quote');      //textarea

echo $this->Form->end('Add');

更详细的日期输入设置:

echo $this->Form->input('birth_dt'array(

    'label' => 'Date of birth',

    'dateFormat' => 'DMY',

    'minYear' => date('Y'- 70,   //70 years ago

    'maxYear' => date('Y'- 18,//18 years ago

));

 

除了部分下面介绍的$option属性外,可以给input()设置任何HTMl属性(例如onfocus事件)。更多信息请查看HtmlHelper$htmlAttributes

 

假设User ModelGroup Model关系为HABTM,在Controller中设置多级变量。比如:

$this->set('groups'$this->User->Group->find('list'));

View文件中,通过以下方式可自动创建select多项选择:

echo $this->Form->input('Group');

假如,数据表之间关系为hasOnebelongTO关系,需要为其创建select多项选择form。在Controller中使用如下代码(User belongTo group

 

$this->set('groups'$this->User->Group->find('list'));

然后, 在view文件Form:

echo $this->Form->input('group_id');

 

如果Model名称包含多个单词,Model名称则必须首字母大写,set时,变量第一个单词小写,后续单词首字母大写。如下:

$this->set('userGroups'$this->UserGroup->find('list'));

// or

$this->set(

    'reallyInappropriateModelNames',

    $this->ReallyInappropriateModelName->find('list')

);

注:尽量避免使用input()创建submit提交按钮,使用submit()代替。

3.2 方法inputs()

方法:FormHelper::inputs()(mixed $fields = null, array $blacklist = null, $options = array())

为$fields内容创建input表格输入,如果$fields和$blacklist都为空,默认创建当前Model包含的所有字段input

除了包含字段input$fields通过 fieldset 和 legend属性设置界面fieldset 和 legend属性$this->Form->inputs(array('legend' => 'My legend')); 将产生默认的'legend' 属性。可通过$fields设置自定义的个性输入。

echo $this->Form->inputs(array(

    'name' => array('label' => 'custom label')

));

除了这些字段控制,inputs()允许你使用一些额外的选项。 

l fieldset设置为false禁用字段集。如果设置为字符串,则为该字段元素名称。 

l legend设置为false来禁用输入图例。设置为字符串提供一个字符串自定义图例文本。

3.3 域名约定

FormHelper非常智能,当你使用它创建一个表单输入,其就会根据当前Model创建表单输入,格式如下:

<input type="text" id="ModelnameFieldname" name="data[Modelname][fieldname]">

如果创建相同的字段名,创建Model表单数组,Controller保存时使用saveAll(),创建格式如下:

echo $this->Form->input('Modelname.0.fieldname');

echo $this->Form->input('Modelname.1.fieldname');

输出HTML内容:

<input type="text" id="Modelname0Fieldname"

    name="data[Modelname][0][fieldname]">

<input type="text" id="Modelname1Fieldname"

    name="data[Modelname][1][fieldname]">

 

FormHelper可使用多种Model内部后缀的方式实现日期输入,如果使用year, month, day, hour, minute, or meridian时出现内容获取问题,请设置name属性覆盖其默认状态,如下:

echo $this->Form->input('Model.year'array(

    'type' => 'text',

    'name' => 'data[Model][year]'

));

3.4 Options设置

FormHelper::input()支持很多输入选项设置,除了input()选项支持设置输入type外,支持HTML表格输入的所有选项设置。下面将一一介绍。

l $options['type']:设置输入类型,除了创建表单中类型,还包括‘file’,‘password’,以及HTML5包含的所有类型。

echo $this->Form->input('field'array('type' => 'file'));

echo $this->Form->input('email'array('type' => 'email'));

输出HTML内容:

<div class="input file">

    <label for="UserField">Field</label>

    <input type="file" name="data[User][field]" value="" id="UserField" />

</div>

<div class="input email">

    <label for="UserEmail">Email</label>

    <input type="email" name="data[User][email]" value="" id="UserEmail" />

</div>

 

l $options['div']:设置包含输入表单的div属性,字符串将设置div类名,数组将设置div属性,键-值属性。或设置为false,禁用div

设置类名,如下:

echo $this->Form->input('User.name'array(

    'div' => 'class_name'

));

输出HTML内容:

<div class="class_name">

    <label for="UserName">Name</label>

    <input name="data[User][name]" type="text" value="" id="UserName" />

</div>

设置很多div属性格式:

echo $this->Form->input('User.name'array(

    'div' => array(

        'id' => 'mainDiv',

        'title' => 'Div Title',

        'style' => 'display:block'

    )

));

输出HTML内容:

<div class="input text" id="mainDiv" title="Div Title"

    style="display:block">

    <label for="UserName">Name</label>

    <input name="data[User][name]" type="text" value="" id="UserName" />

</div>

禁用div输出:

echo $this->Form->input('User.name'array('div' => false)); ?>

输出HTML内容:

<label for="UserName">Name</label>

<input name="data[User][name]" type="text" value="" id="UserName" />

l $options['label']:设置输入表格显示的字符串标签。

echo $this->Form->input('User.name'array(

    'label' => 'The User Alias'

));

输出HTML内容:

<div class="input">

    <label for="UserName">The User Alias</label>

    <input name="data[User][name]" type="text" value="" id="UserName" />

</div>

设置为false,禁用输入标签。

echo $this->Form->input('User.name'array('label' => false));

输出HTML内容:

<div class="input">

    <input name="data[User][name]" type="text" value="" id="UserName" />

</div>

设置为数组,自定义标签的附加选项:

echo $this->Form->input('User.name'array(

    'label' => array(

        'class' => 'thingy',

        'text' => 'The User Alias'

    )

));

输出HTML内容

<div class="input">

    <label for="UserName" class="thingy">The User Alias</label>

    <input name="data[User][name]" type="text" value="" id="UserName" />

</div>

l $options['error']:设置输入内容格式不正确显示信息。设置为false时,禁用错误信息显示。

$this->Form->input('Model.field'array('error' => false));

  如只禁用错误信息,保存字段,设置errorMessage键为false

$this->Form->input('Model.field'array('errorMessage' => false));

注:2.3版本之后,才包含'errorMessage' 属性设置。

如设置其他包含的属性或class,使用如下格式:

$this->Form->input('Model.field'array(

    'error' => array(

        'attributes' => array('wrap' => 'span''class' => 'bzzz')

    )

));

为了防止HTML中的错误信息输出被自动转义,设置子选项escapefalse

$this->Form->input('Model.field'array(

    'error' => array(

        'attributes' => array('escape' => false)

    )

));

覆盖Model错误消息,使用相匹配验证规则名称的键-值:

$this->Form->input('Model.field'array(

    'error' => array('tooShort' => __('This is not long enough'))

));

通过上述内容,可以为Modelvalidation规则设置错误信息。此外,也可以设置国际规则信息。

l $options['before'], $options['between'], $options['separator'], and $options['after']

输入表单中如果需要添加标记(在界面中显示),请使用这些方法。

echo $this->Form->input('field'array(

    'before' => '--before--',

    'after' => '--after--',

    'between' => '--between---'

));

输出HTML内容:

<div class="input">

--before--

<label for="UserField">Field</label>

--between---

<input name="data[User][field]" type="text" value="" id="UserField" />

--after--

</div>

对于radio输入表单,设置separator属性标记分隔每个input/label对:

echo $this->Form->input('field'array(

    'before' => '--before--',

    'after' => '--after--',

    'between' => '--between---',

    'separator' => '--separator--',

    'options' => array('1''2')

));

 

输出HTNL内容:

<div class="input">

--before--

<input name="data[User][field]" type="radio" value="1" id="UserField1" />

<label for="UserField1">1</label>

--separator--

<input name="data[User][field]" type="radio" value="2" id="UserField2" />

<label for="UserField2">2</label>

--between---

--after--

</div>

对于date datetime 类型,设置“separator”改变元素之间的字符串。默认为' - '

l $options['format']:控制Formhelper生成的HTML格式。‘format’支持描述模板。支持的数组有:array('before', 'input', 'between', 'label', 'after','error').

l $options['inputDefaults']:设置表单输入的默认格式。

echo $this->Form->create('User'array(

    'inputDefaults' => array(

        'label' => false,

        'div' => false

    )

));

从设置之后的所有输入表单继承'inputDefaults' 声明的属性。后续也可单独设置覆盖其默认属性。

// No div, no label

echo $this->Form->input('password');

// has a label element

echo $this->Form->input('username'array('label' => 'Username'));

如果需要更改默认设置,使用FormHelper:: inputDefaults()方法。

4. 特定类型input

input()外,FormHelper 可产生多个不同类型input方法。这些可以是input自身,也可以结合其他方法,如label()和error(),产生完全定制的表单格式。

4.1 常用选项

许多不同的input元素支持一组通用的选项设置。所有这些选项都被input()支持。为减少重复介绍,这里只介绍一次,所有元素共有的选项如下:

 

l $options['class']:设置class属性。

echo $this->Form->input('title'array('class' => 'custom-class'));

l $options['id']:设置DOM id属性。

l $options['default']:设置默认值。

echo $this->Form->input('ingredient'array('default' => 'Sugar'));

 

例如在select中,设置默认值为Medium

 

$sizes = array('s' => 'Small''m' => 'Medium''l' => 'Large');

echo $this->Form->input(

    'size',

    array('options' => $sizes'default' => 'm')

);

注:不可以通过'default'设置checkbox默认值。可通过在Controller中设置$this->request->data或设置器checked选项为truefalse实现。

日期和日期时间通过设置“selected”选项来设置默认值。请勿设置'default' => false false值用来禁止输入字段的选择,所以“default=> false无意义。使用“default'=>0

除了上述选项设置,还可以设置任何HTML中包含的属性。

4.2 select, checkbox 和 radio选项设置 

l $options['selected']:选择型输入表单中(select, date, time, datetime),设置选中默认值。

 

echo $this->Form->input('close_time'array(

    'type' => 'time',

    'selected' => '13:30:00'

));

l $options['empty']:设置为true,默认输入为空

在select中,设置为true,默认输入为空,当设置为字符串值时,默认显示为字符串内容。

echo $this->Form->input('field'array(

    'options' => array(12345),

    'empty' => '(choose one)'

));

输出HTNL内容:

<div class="input">

    <label for="UserField">Field</label>

    <select name="data[User][field]" id="UserField">

        <option value="">(choose one)</option>

        <option value="0">1</option>

        <option value="1">2</option>

        <option value="2">3</option>

        <option value="3">4</option>

        <option value="4">5</option>

    </select>

</div>

如果需要在password字段中设置默认值空白,使用'value'=>''代替。

l $options['hiddenField']:某些输入类型(checkboxes, radios),隐藏的input即使没有值,在Controller中调用 $this->request->data方法,内容还是存在的。

<input type="hidden" name="data[Post][Published]" id="PostPublished_"

    value="0" />

<input type="checkbox" name="data[Post][Published]" value="1"

    id="PostPublished" />

 

取消设置 $options['hiddenField'] = false:

 

echo $this->Form->checkbox('published'array('hiddenField' => false));

输出HTML内容:

<input type="checkbox" name="data[Post][Published]" value="1"

    id="PostPublished" />

如果在表单中创建一个组合形式的input。除了第一个input不需设置该选项外,其他input都请设置该选项。如果hidden input在表单中出现了多次,则只有最后一组内容才被保存提交。

下面例子中,只有第三个颜色值会被传递过去,而原色值将被覆盖:

<h2>Primary Colors</h2>

<input type="hidden" name="data[Color][Color]" id="Colors_" value="0" />

<input type="checkbox" name="data[Color][Color][]" value="5"

    id="ColorsRed" />

<label for="ColorsRed">Red</label>

<input type="checkbox" name="data[Color][Color][]" value="5"

    id="ColorsBlue" />

<label for="ColorsBlue">Blue</label>

<input type="checkbox" name="data[Color][Color][]" value="5"

    id="ColorsYellow" />

<label for="ColorsYellow">Yellow</label>

<h2>Tertiary Colors</h2>

<input type="hidden" name="data[Color][Color]" id="Colors_" value="0" />

<input type="checkbox" name="data[Color][Color][]" value="5"

    id="ColorsGreen" />

<label for="ColorsGreen">Green</label>

<input type="checkbox" name="data[Color][Color][]" value="5"

    id="ColorsPurple" />

<label for="ColorsPurple">Purple</label>

<input type="checkbox" name="data[Addon][Addon][]" value="5"

    id="ColorsOrange" />

<label for="ColorsOrange">Orange</label>

禁用第二个输入组“hiddenField'将阻止这种情况发生。

你可以为隐藏字段设置很多不同的值,只需大于0,如“N”

echo $this->Form->checkbox('published'array(

    'value' => 'Y',

    'hiddenField' => 'N',

));

4.3 日期时间选项

l $options['timeFormat']:设置时间格式,有效值包括1224,和null

l $options['dateFormat']:设置日期格式,有效值包括DMY任意组合和null。显示为三者顺序。

l $options['minYear'], $options['maxYear']:设置年份输入最小值和最大值。

l $options['orderYear']:设置年份排序方式,有效值: 升序‘asc和降序‘desc。默认值为desc

l $options['interval']:设置分钟数间隔值。

echo $this->Form->input('Model.time'array(

    'type' => 'time',

    'interval' => 15

));

将创建4个分钟选项,间隔为15分钟。

l $options['round']:根据时间间隔,设置分钟默认值为最大或最小。有效值:updown

5. 形成元素特有方法

先前章节介绍了在View中通过FromHelper创建form表单和表单元素。生成HTML文件时,将包含当前Model属性。比如(假定当前ModelUser):name=data[User][username], id=UserUsername

5.1 FormHelper::label

方法:FormHelper::label(string $fieldName, string $text, array $options)

创建label标签,$fieldName创建DOM id$text label标签值。如$text为空,则label标签值为$fieldName

echo $this->Form->label('User.name');

echo $this->Form->label('User.name''Your username');

输出HTML内容:

<label for="UserName">Name</label>

<label for="UserName">Your username</label>

$options可以是HTML属性的阵列,或被用作类名的字符串:

echo $this->Form->label('User.name'nullarray('id' => 'user-label'));

echo $this->Form->label('User.name''Your username''highlight');

输出HTML内容:

<label for="UserName" id="user-label">Name</label>

<label for="UserName" class="highlight">Your username</label>

5.2 FormHelper::text

方法:FormHelper::text(string $name, array $options)

创建text属性表单,$name影响namedom id选项,$options属性只可定义HTML属性。

echo $this->Form->text('username'array('class' => 'users'));

输出HTML内容:

<input name="data[User][username]" type="text" class="users"

    id="UserUsername" />

5.3 FormHelper::password

方法:FormHelper::password(string $fieldName, array $options)

创建password输入表单:

echo $this->Form->password('password');

输出HTML内容:

<input name="data[User][password]" value="" id="UserPassword"

    type="password" />

5.4 FormHelper::hidden

方法:FormHelper::hidden(string $fieldName, array $options)

创建hidden输入表单:

echo $this->Form->hidden('id');

输出HTML内容:

<input name="data[User][id]" id="UserId" type="hidden" />

表单编辑时($this->request->data包含Model数据),对应id字段的值会自动添加到生成的HTML。例如用于data[User] [ID] =10

 

<input name="data[User][id]" id="UserId" type="hidden" />

5.5 FormHelper::textarea

方法:FormHelper::textarea(string $fieldName, array $options)

创建textarea输入表单:

echo $this->Form->textarea('notes');

输出HTML内容:

<textarea name="data[User][notes]" id="UserNotes"></textarea>

表单编辑模式下($this->request->data包含Model数据),textarea内容会自动导入。比如:

<textarea name="data[User][notes]" id="UserNotes">

This text is to be edited.

</textarea>

设置textarea'escape'选项,决定是否自动导入textarea内容。默认为true

echo $this->Form->textarea('notes'array('escape' => false);

// OR....

echo $this->Form->input(

    'notes',

    array('type' => 'textarea''escape' => false)

);

l Options

除了常用选项,textarea还有部分特殊选项设置。

n $options['rows'], $options['cols']:设置textarea行和列。

echo $this->Form->textarea(

    'textarea',

    array('rows' => '5''cols' => '5')

);

输出HTML内容:

<textarea name="data[Form][textarea]" cols="5" rows="5" id="FormTextarea">

</textarea>

5.6 FormHelper::checkbox

方法:FormHelper::checkbox(string $fieldName, array $options)

创建checkbox输入表单,该方式还创建一个hidden表单输入强制指定字段数据的默认提交。

echo $this->Form->checkbox('done');

输出HTML内容:

<input type="hidden" name="data[User][done]" value="0" id="UserDone_" />

<input type="checkbox" name="data[User][done]" value="1" id="UserDone" />

设置$options属性:

echo $this->Form->checkbox('done'array('value' => 555));

输出HTML内容:

<input type="hidden" name="data[User][done]" value="0" id="UserDone_" />

<input type="checkbox" name="data[User][done]" value="555" id="UserDone" />

如果比希望自动创建hidden输入表单,需如下设置:

echo $this->Form->checkbox('done'array('hiddenField' => false));

输出HTML内容:

<input type="checkbox" name="data[User][done]" value="1" id="UserDone" />

5.7 FormHelper::radio

方法:FormHelper::radio(string $fieldName, array $options, array $attributes)

创建radio输入表单

$attributes参数选项:

l $attributes['value']:设置默认选择值。

l $attributes['separator']:设置表单之间显示内容。

l $attributes['between']:设置legend和第一个表单之间显示内容。

l $attributes['disabled']:设置为true。创建的所有radio表单输入将不可使用(2.1版本之后增加)。

l $attributes['legend']:设置所有radio包含于legendfieldset之间。设置为false取消。

$options = array('M' => 'Male''F' => 'Female');

$attributes = array('legend' => false);

echo $this->Form->radio('gender'$options$attributes);

输出HTML内容:

<input name="data[User][gender]" id="UserGender_" value=""

    type="hidden" />

<input name="data[User][gender]" id="UserGenderM" value="M"

    type="radio" />

<label for="UserGenderM">Male</label>

<input name="data[User][gender]" id="UserGenderF" value="F"

    type="radio" />

<label for="UserGenderF">Female</label>

如不需要hidden表单输入,$attributes['value']为其中一个值或设置为false

5.8 FormHelper::select

方法:FormHelper::select(string $fieldName, array $options, array $attributes)

创建select输入表单。设置$attributes['value']为默认选中值。设置empty选项为false关闭表单空选项。

$options = array('M' => 'Male''F' => 'Female');

echo $this->Form->select('gender'$options);

输出HTML内容:

<select name="data[User][gender]" id="UserGender">

<option value=""></option>

<option value="M">Male</option>

<option value="F">Female</option>

</select>

Select中,可设置escape选项为truefalse决定HTML是否实体编码$option制定的选项内容。

$options = array('M' => 'Male''F' => 'Female');

echo $this->Form->select('gender'$optionsarray('escape' => false));

l $attributes['options']:允许设置为select选择项,或radio单选项,除非类型指定为radio,其默认输出为select选择项。

echo $this->Form->select('field'array(1,2,3,4,5));

Output:

<select name="data[User][field]" id="UserField">

    <option value="0">1</option>

    <option value="1">2</option>

    <option value="2">3</option>

    <option value="3">4</option>

    <option value="4">5</option>

</select>

也可以设置为key-value选项,如下:

echo $this->Form->select('field'array(

    'Value 1' => 'Label 1',

    'Value 2' => 'Label 2',

    'Value 3' => 'Label 3'

));

输出HTML内容:

<select name="data[User][field]" id="UserField">

    <option value="Value 1">Label 1</option>

    <option value="Value 2">Label 2</option>

    <option value="Value 3">Label 3</option>

</select>

如果需生成可选择Group(数据分组格式)的select表单,这适用于多个复选框和单选按钮。

 

$options = array(

   'Group 1' => array(

      'Value 1' => 'Label 1',

      'Value 2' => 'Label 2'

   ),

   'Group 2' => array(

      'Value 3' => 'Label 3'

   )

);

echo $this->Form->select('field'$options);

Output:

<select name="data[User][field]" id="UserField">

    <optgroup label="Group 1">

        <option value="Value 1">Label 1</option>

        <option value="Value 2">Label 2</option>

    </optgroup>

    <optgroup label="Group 2">

        <option value="Value 3">Label 3</option>

    </optgroup>

</select>

l $attributes['multiple']:设置是否可以多选

echo $this->Form->select(

    'Model.field',

    $options,

    array('multiple' => true)

);

设置'multiple'为checkbox,将自动创建一列可多选的checkbox。

$options = array(

    'Value 1' => 'Label 1',

    'Value 2' => 'Label 2'

);

echo $this->Form->select('Model.field'$optionsarray(

    'multiple' => 'checkbox'

));

输出HTML内容:

<div class="input select">

   <label for="ModelField">Field</label>

   <input name="data[Model][field]" value="" id="ModelField"

    type="hidden">

   <div class="checkbox">

      <input name="data[Model][field][]" value="Value 1"

        id="ModelField1" type="checkbox">

      <label for="ModelField1">Label 1</label>

   </div>

   <div class="checkbox">

      <input name="data[Model][field][]" value="Value 2"

        id="ModelField2" type="checkbox">

      <label for="ModelField2">Label 2</label>

   </div>

</div>

l $attributes['disabled']:如创建checkboxes。设置checkbox可用或不可用。默认为false。所有不可用,设置为true

$options = array(

    'Value 1' => 'Label 1',

    'Value 2' => 'Label 2'

);

echo $this->Form->select('Model.field'$optionsarray(

    'multiple' => 'checkbox',

    'disabled' => array('Value 1')  //added in version 2.3

));

 

输出HTML内容:

<div class="input select">

   <label for="ModelField">Field</label>

   <input name="data[Model][field]" value="" id="ModelField"

    type="hidden">

   <div class="checkbox">

      <input name="data[Model][field][]" disabled="disabled"

        value="Value 1" id="ModelField1" type="checkbox">

      <label for="ModelField1">Label 1</label>

   </div>

   <div class="checkbox">

      <input name="data[Model][field][]" value="Value 2"

        id="ModelField2" type="checkbox">

      <label for="ModelField2">Label 2</label>

   </div>

</div>

5.9 FormHelper::file

方法:FormHelper::file(string $fieldName, array $options)

创建文件上传输入表单,需设置enctype为“multipart/form-data”,因此创建表单时,需以下格式:

echo $this->Form->create('Document'array(

    'enctype' => 'multipart/form-data'

));

// OR

echo $this->Form->create('Document'array('type' => 'file'));

如下示例中之一加入view Form代码中。

echo $this->Form->input('Document.submittedfile'array(

    'between' => '<br />',

    'type' => 'file'

));

// OR

echo $this->Form->file('Document.submittedfile');

由于HTML本身的局限性,不能把默认值导入“file”字段。每次显示时,里面的值是空的。 

一旦提交,file字段提交一个可扩展的数据数据到后台脚本。

上面的例子中,提交的数据将是如下格式,在UNIX系统中,‘tmp_name’路径将不同:

$this->request->data['Document']['submittedfile'= array(

    'name' => 'conference_schedule.pdf',

    'type' => 'application/pdf',

    'tmp_name' => 'C:/WINDOWS/TEMP/php1EE.tmp',

    'error' => 0,

    'size' => 41737,

);

 

6. 创建按钮和提交元素

7. 创建日期和时间的输入

8. 显示并检查错误

9. 默认设置所有字段

10. 包含SecurityComponent

11. 2.0 更新内容

$selected参数设置删除。所有$selected参数设置通过$attributes['value']实现,简化了FormHelper方法,减少参数数量,减少 $selected设置的重复。影响的方法有:

l FormHelper::select()

l FormHelper::dateTime()

l FormHelper::year()

l FormHelper::month()

l FormHelper::day()

l FormHelper::hour()

l FormHelper::minute()

l FormHelper::meridian()

默认的url路径为当前action。可通过设置$this->Form->create()方法中参数 $options['url']覆盖默认路径。

FormHelper::hidden():隐藏字段不再移除class属性。这意味着,如果有隐藏字段的验证错误,错误字段类名称将被应用。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值