Разработчики:

By Woody Gilk, © 2007Quick Form Generation

Easily set up and validate forms with a custom model and view.

This tutorial will focus on showing you how to setup an easy and reusable form generator using models and views. The example here is for a user login form. This tutorial does not deal with database interaction, but only building, validating, and fetching the form data.

This tutorial does not use the PEAR package HTML_QuickForm2, but uses built-in Kohana functionality.

The Model

First, we need to create a model. Our model will allow us to set the form title and action, the Validation rules, and inputs. It will also handle validation automatically.

 

This file is included in Kohana by default as system/models/form.php.

One thing to note about our model is that most of the methods use return $this;. This allows chaining:

$form = $this->load->model('form', TRUE)
        ->title('User Login')
        ->action('user/login');
 

All of the form methods except validate and build can be chained together.

The View

In order to display our form, we need a view. By default, the model will load a view called kohana_form, but you are free to change the default name, or use a custom template with the generate($template_name) method.

 

This file is included in Kohana by default as system/views/kohana_form.php. You can override the default form by creating application/views/kohana_form.php.

That concludes the entire tutorial. From here, you can expand the Form model to handle database connections, or even extend the model with another model, to handle specific forms. You can modify the view to suit your preferred way of templating forms, or use a custom view for specific forms.

For more information about handling database interaction in your forms, I recommend looking at the Model Validation tutorial.

Questions or Comments?

Feel free to send me questions and comments, my email address is woody.gilk@kohanaphp.com.