Jump to content
Larry Ullman's Book Forums

Sharing Model Methods In Views


lrzins
 Share

Recommended Posts

Hi, I am having to use the same Model methods in several different views. For example, in several different views for creating a new record, I have forms that have a drop down list of years from which to choose. I can add the same method getYears() to each model, and call the method from _form.php, like so:

 

<?php echo $form->dropDownList($model, 'year_entered', $model->getYears(), array('empty' => 'Select Year')); ?>

 

Or, I can reuse that method from another view like so:

 

<?php echo $form->dropDownList($model, 'year', OtherModel::getYears(), array('empty' => 'Select Year')); ?>

 

So then I thought, why not create a class just to hold shared methods, like so:

 

In models/SharedStuff.php:

 

class SharedStuff extends CActiveRecord
{

     public function getYears()
     {
           $current_year=date('Y');
           $end_year=$current_year - 20;
           for ($year = $current_year; $year >= $end_year; $year--) {
                  $year_list[$year] = $year;
           }
           return $year_list;
     }
}

 

Which can be referenced from any _form.php file like so:

 

<?php echo $form->dropDownList($model, 'year', SharedStuff::getYears(), array('empty' => 'Select Year')); ?>

 

I guess another way to do this, is to move the SharedStuff.php class into the "components" directory, and then extend this class in the model files, but the approach above seems pretty clean.

 

Is there a better way to share methods between different views, and I suppose controllers and models too? Am I missing something?

 

Thanks for any advice,

 

Larry Z.

Link to comment
Share on other sites

I guess you could make your own widget for the getYears() method which needs to be reusable. You could add a full class to the components folder but that method would be better if it was a class with several related methods. If you just needed a small bit of code that had nothing in relation to it then i would go with making your own widget.

 

Here is a link to how to do that in the Yii Definitive Guide.

 

http://www.yiiframework.com/doc/guide/1.1/en/extension.create

Link to comment
Share on other sites

 Share

×
×
  • Create New...