Jump to content
Larry Ullman's Book Forums

Sharing Model Methods In Views

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()
           $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 post
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.



Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...