Best Practice for theming

I want to apply themes depending on a database table that contains information about skins and the URL. I was going to edit the config then it occurred to me that the db wouldnt be working at that stage in the page lifecycle.

Where is the correct place to do something like:

  • look up sudomain in db

  • apply correct theme based on subdomain

I apologise in advance if I should have read the manual more carefully!!!

You can do in beforeControllerAction

Would that have to be in every Controller? Is there no single place that I could do this?

Gii generates a base controller for you (Controller.php), in the protected/components folder.

/Tommy

I’m sorry - I am just not getting how to do this. And I have been googling and reading for hours! Can anyone give me just a little more detail as to where I can plug in this code to change the theme based on some setting in the DB?

OK - so what I now do is in /components/Controller.php I added




    public function beforeRender($view) {

        if (isset($_REQUEST['aid'])) {

            $aid=$_REQUEST['aid'];

            //look up in DB and get the right theme

            $aff=Affiliate::model()->findByPk($aid);

            if ($aff<>null) {

                //override the theme if one is found

                yii::app()->theme=$aff->theme;

            }

        }

        return true;

    }



Not sure this is what you were saying but it seems to work.

My solution works fine except that it falls down on Ajax calls since these dont trigger the render. Any ideas would be welcome!

Like zaccaria (sort of) suggested, you can use beforeAction(). I believe an overridden init() would be fine too.

/Tommy

I would be glad to if you could tell me how to! Where? It doesnt seem to work to override in the controller.

I’ve never used beforeAction, it seems to be intended for a specific action !?

The init() link a supplied was completely wrong, sorry for that. This one is better. Just add the method to Controller.php like this




public function init()

{

  parent::init();

  // your code here

}



BTW what are your intention with the ajax, especially without calling render()? To the best of my knowledge, for a theme switch would need to do a complete render(). Not even a renderPartial() will do, since the layout will not be included.

/Tommy

I tried the theming in render - that worked fine.

The problem is that there is a currency conversion that is dependent on the theme (as in affiliate) that is incorrect since the conversion figures are rendered via ajax from a front page. The page is themed correctly (according to the hook in render) but the ajax call doesnt trigger this hook so the affiliate is set wrong and the ajax returns the wrong result.

Thanks - init() does it for me.