When you use form builder to create a form, you must transfer a array and a model as parameter to CForm like this:
$array = include('blogEditForm.php'); // blogEditForm.php return a array
$model = new BlogActiveRecord();
$form = CForm($array, $model);
//after this you can use $form and display it
$form->render();
But, it is impossible if $model is not a CModel. For example, if you wanna display a form to collection same data and save the data to files or in a single field of a table after serialized.
I got a idea form CForm that I can build a form by a array. why can't I build a model by a array ? Now, this virtual model is actually what you want. It's a simple calss extends CModel, but I add same simple functions to help you build a model by a array.
PS: I haven't has fully test for it. If there are same mistake, please can tell me.
In Chinese: 使用一个数组来通过VirtualModel来生成model,就像用一个数组通过CForm生成一个表单一样。 中文使用说明
Documentation ¶
Requirements ¶
- Yii 1.0 or above
Installation ¶
- Extract the release file under protected/extensions/
Usage ¶
Create a config file.
The config array is linke the array for CForm. VirtualModel will use label, default and rules to create model, then, leave others to CForm.
return array(
  'email_address'=>array(
     'type'=>'text',
     'label'=>'The email address',
     'default'=>'you@example.com',
     'rules'=>array(
          array('email', 'email'),
     ),
     // other attribute for CForm
   ),
   // other fields
);
Create your Model
Yii::import('ext.XVirtualModel');
class YourVirtualModel extends XVirtualModel
{
   //override save()
   public function save()
   {
       //save the data in your way
       //data is stored in $this->_values
   }
   //override loadValues()
   public function loadValues()
   {
       //load the data in your way
   }
}
use it
$config = 'application.config.YourVirtualModel';
Yii::import('application.extensions.YourVirtualModel');
$model = new YourVirtualModel($config);
//$model->formMap can return a array for CForm, but you must add same thing
$formMap = $model->formMap;
$formMap['action'] = array('save');
$formMap['title'] => 'Input your email here';
$form = new CForm($formMap, $model);
//Then you can use this form as your will
Change Log ¶
- Mar 30, 2012
- fix bug of rules reported by 未来(http://www.yiibook.com) 
- June 13, 2010
- Initial release.
Re Asgaroth
Ok, it is a good idea!
CFormModel
Why not just using CFormModel instead of an array? try to keep it OOP at all times, its a good practice.
and if you want to manipulate the data after form submition you can always access the CFormModel with $form->model.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.