Yii 1.1: virtualmodel

1 follower

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

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生成一个表单一样。 中文使用说明



  • Yii 1.0 or above


  • Extract the release file under protected/extensions/


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(
     'label'=>'The email address',
          array('email', 'email'),
     // other attribute for CForm
   // other fields

Create your Model

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';
$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

Total 2 comments

#227 report it
dongbeta at 2010/08/04 08:20am
Re Asgaroth

Ok, it is a good idea!

#351 report it
Asgaroth at 2010/07/01 03:58pm

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.

Leave a comment

Please to leave your comment.

Create extension
  • Yii Version: 1.1
  • License: New BSD License
  • Developed by: dongbeta
  • Category: Others
  • Votes: +2 / -2
  • Downloaded: 598 times
  • Created on: Jun 13, 2010
  • Last updated: Mar 29, 2012