Automagic Form Elements
First, let’s look at some of the more automatic form creation methods in the FormHelper. The main method we’ll look at is input(). This method will automatically inspect the model field it has been supplied in order to create an appropriate input for that field.
| Column Type | Resulting Form Field |
|---|---|
| string (char, varchar, etc.) | text |
| boolean, tinyint(1) | checkbox |
| text | textarea |
| text, with name of password, passwd, or psword | password |
| date | day, month, and year selects |
| datetime, timestamp | day, month, year, hour, minute, and meridian selects |
| time | hour, minute, and meridian selects |
For example, let’s assume that my User model includes fields for a username (varchar), password (varchar), approved (datetime) and quote (text). I can use the input() method of the FormHelper to create appropriate inputs for all of these form fields.
<?php echo $form->create(); ?>
<?php
echo $form->input('username'); //text
echo $form->input('password'); //password
echo $form->input('approved'); //day, month, year, hour, minute, meridian
echo $form->input('quote'); //textarea
?>
<?php echo $form->end('Add'); ?>
<?php echo $form->create(); ?><?phpecho $form->input('username'); //textecho $form->input('password'); //passwordecho $form->input('approved'); //day, month, year, hour, minute, meridianecho $form->input('quote'); //textarea?><?php echo $form->end('Add'); ?>
A more extensive example showing some options for a date field:
echo $form->input('birth_dt', array( 'label' => 'Date of birth'
, 'dateFormat' => 'DMY'
, 'minYear' => date('Y') - 70
, 'maxYear' => date('Y') - 18 ));
echo $form->input('birth_dt', array( 'label' => 'Date of birth', 'dateFormat' => 'DMY', 'minYear' => date('Y') - 70, 'maxYear' => date('Y') - 18 ));
And to round off, here's an example for creating a hasAndBelongsToMany select. Assume that User hasAndBelongsToMany Group. In your controller, set a camelCase plural variable (group -> groups in this case, or ExtraFunkyModel -> extraFunkyModels) with the select options. In the controller action you would put the following:
$this->set('groups', $this->User->Group->find('list'));
$this->set('groups', $this->User->Group->find('list'));
And in the view a multiple select can be expected with this simple code:
echo $form->input('Group');
echo $form->input('Group');
If you want to create a select field while using a belongsTo- or hasOne-Relation, you can add the following to your Users-controller (assuming your User belongsTo Group):
$this->set('groups', $this->User->Group->find('list'));
$this->set('groups', $this->User->Group->find('list'));
Afterwards, add the following to your form-view:
echo $form->input('group_id');
echo $form->input('group_id');


Коментарии:
Добавить коментарий