You can store application parameters in your configuration file protected/config/main.php
that we can access using Yii::app()->params['paramName']
. When your application uses the JavaScript code, it is handy to have these parameters available for it. Let's see how to do it in a simple and effective way.
yiic webapp
tool. It should generate an application parameters array in protected/config/main.php
:'params'=>array( // this is used in contact page 'adminEmail'=>'[email protected]', ),
'params'=>array( // this is used in contact page 'adminEmail'=>'[email protected]', 'alert' => array( 'enabled' => true, 'message' => 'Hello there!', ), ),
protected/controllers/AlertController.php
as follows:<?php class AlertController extends Controller { function actionIndex() { $config = CJavaScript::encode(Yii::app()->params->toArray()); Yii::app()->clientScript->registerScript('appConfig', "var config = ".$config.";", CClientScript::POS_HEAD); $this->render('index'), } }
protected/views/alert/index.php
as follows:<script> if(config && config.alert && config.alert.enabled && config.alert.message){ alert(config.alert.message); } </script>
alert
controller of the index
action, you should get a standard JavaScript alert window saying Hello there!, as shown in the following screenshot:3.133.109.30