Свежайшие Пирожки от CakePHP по-русски

Полнейшее руководство CakePHP 1.2 на русском языке, горячие новости и полезные статьи

Creating Forms

The first method you’ll need to use in order to take advantage of the FormHelper is create(). This special method outputs an opening form tag.

create(string $model = null, array $options = array())

All parameters are optional. If create() is called with no parameters supplied, it assumes you are building a form that submits to the current controller, via either the add() or edit() action. The default method for form submission is POST. The form element also is returned with a DOM ID. The ID is generated using the name of the model, and the name of the controller action, CamelCased. If I were to call create() inside a UsersController view, I’d see something like the following output in the rendered view:

Простой текст
  1. <form id="UserAddForm" method="post" action="/users/add">

The create() method allows us to customize much more using the parameters, however. First, you can specify a model name. By specifying a model for a form, you are creating that form's context. All fields are assumed to belong to this model (unless otherwise specified), and all models referenced are assumed to be associated with it. If you do not specify a model, then it assumes you are using the default model for the current controller.

Простой текст
  1. <?php echo $form->create('Recipe'); ?>
  2. //Output:
  3. <form id="RecipeAddForm" method="post" action="/recipes/add">

This will POST the form data to the add() action of RecipesController. However, you can also use the same logic to create an edit form. The FormHelper uses the $this->data property to automatically detect whether to create an add or edit form. If $this->data contains an array element named after the form's model, and that array contains a non-empty value of the model's primary key, then the FormHelper will create an edit form for that record. For example, if we browse to http://site.com/recipes/edit/5, we might get the following:

Простой текст
  1. // controllers/recipes_controller.php:
  2. <?php
  3. function edit($id = null) {
  4. if (empty($this->data)) {
  5. $this->data = $this->Recipe->findById($id);
  6. } else {
  7. // Save logic goes here
  8. }
  9. }
  10. ?>
  11.  
  12. // views/recipes/edit.ctp:
  13. // Since $this->data['Recipe']['id'] = 5, we should get an edit form
  14. <?php echo $form->create('Recipe'); ?>
  15.  
  16. //Output:
  17. <form id="RecipeEditForm" method="post" action="/recipes/edit/5">
  18. <input type="hidden" name="_method" value="PUT" />

that since this is an edit form, a hidden input field is generated to override the default HTTP method.

The $options array is where most of the form configuration happens. This special array can contain a number of different key-value pairs that affect the way the form tag is generated.