Tuesday, May 29, 2012

YII Adding a parameter to the Action

This is for security and better control of your website.

If you are adding a parameter to your action and you are using that parameter to get data from the database, make sure you throw error page when there is no data from the database.

In config/main.php - for managing URL with alias
'components'=>array(
      ...
      'urlManager' => array(
           'post/<alias>' => 'post/page',
));
URL 
http://www.example.com/post/alias_name_here
Controller
<?php
class PostController extends Controller {
       ...
       public function actionPage($alias) {
             echo $alias;
             /* Using $alias to get data */
            $alias_data = Post::model()->find(array(
                'condition'=>"active='Y' AND alias='".$alias."'",
                'order'=>'id DESC',
                'select'=>'title, content',
                'limit'=>1,
            ));
           if (is_object($alias_data)) {
                 /* Display alias_data */
                 ...
           } else
                 /* Through error page when there is no data */
                 throw new CHttpException(404,'The specified page cannot be found.');
           }
      }
}

No comments: