Yii Tutorial on Yii Create Page

now we are going to create a “hello world” page in your application. to create a page, we must create an action and a view.

actions are declared in controllers. the end user will receive the execution result of an action.

step 1 − declare the speak action in the existing sitecontroller, which is defined in the class file controllers/sitecontroller.php.

<?php 
   namespace app\controllers; 
   use yii; 
   use yii\filters\accesscontrol; 
   use yii\web\controller; 
   use yii\filters\verbfilter; 
   use app\models\loginform; 
   use app\models\contactform; 
   class sitecontroller extends controller { 
      /* other code */ 
      public function actionspeak($message = "default message") { 
         return $this->render("speak",['message' => $message]); 
      } 
   } 
?>

we defined the speak action as a method called actionspeak. in yii, all action methods are prefixed with the word action. this is how the framework differentiates action methods from non-action ones. if an action id requires multiple words, then they will be concatenated by dashes. hence, the action id add-post corresponds to the action method actionaddpost.

in the code given above, the ‘out’ function takes a get parameter, $message. we also call a method named ‘render’ to render a view file called speak. we pass the message parameter to the view. the rendering result is a complete html page.

view is a script that generates a response's content. for the speak action, we create a speak view that prints our message. when the render method is called, it looks for a php file names as view/controllerid/vewname.php.

step 2 − therefore, inside the views/site folder create a file called speak.php with the following code.

<?php 
   use yii\helpers\html; 
?> 
<?php echo html::encode($message); ?> 

note that we html-encode the message parameter before printing to avoid xss attack.

step 3 − type the following in your web browser http://localhost:8080/index.php?r=site/speak&message=hello%20world.

you will see the following window −

speak php file

the ‘r’ parameter in the url stands for route. the route's default format is controllerid/actionid. in our case, the route site/speak will be resolved by the sitecontroller class and the speak action.