Whether the model extends CFormModel or CActiveRecord, the important thing to remember is that the form is tied to a model. This is significant because it’s the model that dictates what form elements should exist, controls validation of the form data, and even defines the form’s labels (e.g., “First Name” for the firstName attribute), and so forth.
When you use Gii to auto-generate CRUD functionality for a model, the framework creates a form for you in a file named _form.php. Any view file in Yii that starts with an underscore is intended to be an include. Naturally, the controller dictates which primary view file gets rendered. Also understand that the same _form.php file is intended to be used whether the form is for creating new records or updating existing ones. Yii will take care of populating the form’s elements with the model’s current value when an update is being performed.
Because forms are normally tied to models, you’ll need access to a model instance when you go to create the form. Before getting to the view and its form, let’s be clear as to how the view accesses the specific model. A controller may have this code:
public function actionCreate() {
$model=new Page;
// Code for validation and redirect upon save.
// If not saved, render the create view
$this->render('create',array(
'model'=>$model
));
}
The create.php view file will include _form.php, passing along the model instance in the process:
<?php
echo $this->renderPartial('_form', array('model'=>$model));
?>
_form.php has access to the model instance and can create the form tied to that model. Once the form view file has access to the model, it can create form elements in one of two ways
Invoking the CHtml class methods directly
Using the CActiveForm widget
Comments
Post a Comment