[SOLVED] How to run a javascript function on body load?

Hi, I am a newbie on Yii framework. I wonder how to load a javascript function on body load? (i.e. <body onload="myInitialFunc()">).

You can do this in your layout file directly in the body tag

<body onload="<?php echo Yii::app()->controller->onloadFunctions; ?">

$onloadFunctions should be defined as a property of your controller like

public &#036;onloadFunctions;

then somewhere assign it a value like this:


Thanks a lot, that’s very useful!!

[Solved?] How can you say that?

If it was solved all the pieces would be shown.

Where is this mysterious onloadFunctions defined?

You say in your reply that

$onloadFunctions should be defined as a property of your controller , however, you fall short of sample code

with that definition. is:

public $onloadFunctions;

enough of a definition?

I just searched contents of every file on an existing Yii project including the yii folder itself with not a thing mentioned about onloadFunctions even case insensitive searches.

I checked the Yii documentation and found nothing in the Yii guide

I did find references of window.onload= from embeded javascript but that does not do the same thing

can someone explain where this code is defined anywhere? Yii framework seems to know nothing about


Is it possible a lot of these answers are absolete or specific to versions of Yii??

You’ll have to understand the concepts of Yii to know what phpdevmd ment. Every controller in your app can have properties that you define. Let’s assume we are using SIteController:

class MyController extends Controller


     public $onloadFunction='AJavascriptFunction();';


class SiteController extends MyController


     ///MyController also has a property $onloadFunction as it is inherited

     public function actionDisplay()




     public function actionDisplayWithOtherOnloadFunction()






if the layout file gets altered like mentioned

<body onload="<?php echo Yii::app()->controller->onloadFunction; ?">

it will replace the PHP code with ‘AJavascriptFunction();’ when a calling site/display and with ‘AnotherFunction();’ when calling site/displayWithAnotherOnloadFunction

Hope that makes it a bit clearer. The reason I created a custom Controller called MyController is that I want to make clear that this is a customized Controller and not an “original” Yii Controller. Every Controller in your app should inherit from this one because the layout file will always ask for the onLoadFunction property for EVERY request (more specific: Yii::app()->controller->onLoadFunction will do that). So if you don’t inherit from MyController you won’t have the property => will get an error undefined property

Thanks to phpdevmd for the idea. Nice!