Now, we will create a simple news list in a view named itemsList
. We will point to this view from NewsController
, so we have to:
news
folder under basic/views
, that NewsController
will use as the base folder to search for the views to be rendered (according to the view names' rules explained in the previous chapter)itemsList.php
file under basic/views/news
Now, open basic/views/news/itemsList.php
, create an array with a list of data and display the output with a simple table of items:
<?php $newsList = [ [ 'title' => 'First World War', 'date' => '1914-07-28' ], [ 'title' => 'Second World War', 'date' => '1939-09-01' ], [ 'title' => 'First man on the moon', 'date' => '1969-07-20' ] ]; ?> <table> <tr> <th>Title</th> <th>Date</th> </tr> <?php foreach($newsList as $item) { ?> <tr> <td><?php echo $item['title'] ?></td> <td><?php echo $item['date'] ?></td> </tr> <?php } ?> </table>
Then, we need to create an action provided by a function named actionItemsList
that will be rendered by http://hostname/basic/web/index.php?r=news/items-list
.
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Pay attention to names for routes, controllers, and actions:
news/items-list
(lowercase and words separated by dashes);NewsController
(uppercase with the word Controller in the end);NewsController
is actionItemsList
(the function name has action
word as prefix, dashes in the route are removed, and the first letter of each word is in uppercase);The function to append in the NewsController
class is as follows:
public function actionItemsList() { return $this->render('itemsList'); }
The render()
method that belongs to yiiwebController
, displays in the layout content of the view passed as the first parameter. When the framework is looking for the view, it will append .php
extension to the name passed as the first parameter of the render()
method and it will look for it in basic/view/news
. The last member of the path is the name that is calling the render()
method.
Now, we can point to http://hostname/basic/web/index.php?r=news/items-list
, to see our beautiful table!
18.189.22.136