posted by Roopz on May 14, 2014

List of Column Types in Yii Migration

The following was extract from the yii CDbSchema::getColumnType. It maps the string value defined in yii migration.
  • pk: an auto-incremental primary key type, will be converted into “int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY”
  • string: string type, will be converted into “varchar(255)”
  • text: a long string type, will be converted into “text”
  • integer: integer type, will be converted into “int(11)”
  • boolean: boolean type, will be converted into “tinyint(1)”
  • float: float number type, will be converted into “float”
  • decimal: decimal number type, will be converted into “decimal”
  • datetime: datetime type, will be converted into “datetime”
  • timestamp: timestamp type, will be converted into “timestamp”
  • time: time type, will be converted into “time”
  • date: date type, will be converted into “date”
  • binary: binary data type, will be converted into “blob”
posted by Roopz on January 6, 2014
Quick Start tutorial Yii Framework 1.1.8

Step 1: Download the Yii

    You can find the last verse in stable:
    After downloading unzip the folder inside to inside of your server (htdocs on Apache, for example) web folder and rename the unzipped to "yii" folder.
Step 2: Creating the application

    2.1) Check the requirements of PHP and server http://localhost/yii/requirements/index.php
        Not mandatory that all items are marked as "OK", but recommended. In case you are using the MySQL database, the necessary extensions to the SQLite and PostgreSQL.
    Photo # 1.jpg
    2.2) Open the command prompt or terminal, navigate at the web server folder, and type:
            yii / framework / webapp yiic nomeDaAplicacao
        [/ Code]
        On Windows operating systems, using backslash ("\") in the folder path.
        The "yii" folder should be mandatory within your web folder.
        If all goes well you will be asked: Create a Web application under '/ caminhoParaPastaWeb / nomeDaAplicacao'? [Yes | No]
        Enter: Yes
        Check your browser if your project was created: http://localhost/nomeDaAplicacao
        # 2.jpg image
Step 3: Configuring the application

    3.1) Open the nomeDaAplicacao / protected / config / main.php file in a text editor.
        Uncomment omdulo Gii to habilit it in line 23:
            / / Uncomment to The Following enable the Gii tool
            / *
            'Gii' => array (
                'Class' => 'system.gii.GiiModule'
                'Password' => 'Enter Your Password Here'
                / / If removed, Gii defaults to localhost only. Edit carefully to taste.
                'IpFilters' => array ('127 .0.0.1', ':: 1'),
            * /
        [/ Code]
        Choose a password to enter omdulo and where is written "Enter Your Password Here".
        In line 40, uncomment the following:
            / / Uncomment to enable The Following URLs in path-format
            / *
            'UrlManager' => array (
                'UrlFormat' => 'path',
                'Rules' => array (
                    '<controller:\w+> / <id:\d+>' => '<controller> / View',
                    '<controller:\w+> / <action:\w+> / <id:\d+>' => '<controller> / <action>'
                    '<controller:\w+> / <action:\w+>' => '<controller> / <action>'
            * /
        [/ Code]
        and add the line of code "'showScriptName' => false,":
            'UrlFormat' => 'path', / / ​​j exists
            'ShowScriptName' => false, / / ​​add
            'Rules' => array (/ / j exists
        [/ Code]
        This will enable the use of URL's amigveis.
        In line 53, uncomment:
            / / The Following uncomment to use the MySQL database
            / *
            'Db' ​​=> array (
                'ConnectionString' => 'mysql: host = localhost, dbname = testdrive'
                'EmulatePrepare' => true,
                'Username' => 'root',
                'Password' =>'',
                'Charset' => 'utf8',
            * /
        [/ Code]
        Here you configure the connection to the MySQL server informing the host, database name, User and Password.
Step 4: Preparing the server and the application to use URL's amigveis

        4.1) On Apache servers you need to enable omdulo Rewrite.
            Open the Apache configuration file (in Windows: httpd.conf) and uncomment the line:
                Rewrite_module # LoadModule modules /
            [/ Code]
            Remove the "#" character.
            Restart Apache.
            If your server is Windows IIS, enable anlogo omdulo this.
        4.2) The URL that you see still http://localhost/nomeDaAplicacao/index.php/controller/action
            To get the "index.php" from the URL must create an htaccess file in the root of your project with the following contents.:
                RewriteEngine On
                RewriteBase /
                RewriteCond% {REQUEST_FILENAME}!-F
                RewriteCond% {REQUEST_FILENAME}!-D
                RewriteRule ^ (. *) \? NomeDaAplicacao * $ / index.php / $ 1 [L, QSA]
            [/ Code]
            Replace "nomeDaAplicacao" with the name of your application.
            If your server is IIS Windows you need to create a web.config file in the root of your project with the following contents:
                <? Xml version = "1.0" encoding = "UTF-8">
                                <rule name="Main Rule" stopProcessing="true">
                                    <match url=".*" />
                                    <conditions logicalGrouping="MatchAll">
                                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                                    </ Conditions>
                                    <action> type="Rewrite" url="index.php" />
                                </ Rule>
                            </ Rules>
                        </ Rewrite>
                    </ System.webServer>
                </ Configuration> 
            [/ Code]
            Now the syntax of their URLs Esto as: http://localhost/nomeDaAplicacao/controller/action
            If your Apache server and still is in this form, verify in the server configuration (httpd.conf) file and change the permissions "AllowOverride None" to "AllowOverride All".
posted by Roopz on January 6, 2014


This is a login template (protected/views/site/login.php):


$this->pageTitle=Yii::app()->name . ' - Login';







<p>Please fill out the following form with your login credentials:</p>



<?php $form=$this->beginWidget('CActiveForm', array(



)); ?>



<p>Fields with <span>*</span> are required.</p>


<?php echo $form->labelEx($model,'username'); ?>

<?php echo $form->textField($model,'username'); ?>

<?php echo $form->error($model,'username'); ?>



<?php echo $form->labelEx($model,'password'); ?>

<?php echo $form->passwordField($model,'password'); ?>

<?php echo $form->error($model,'password'); ?>


Hint: You may login with <tt>demo/demo</tt> or <tt>admin/admin</tt>.




<?php echo $form->checkBox($model,'rememberMe'); ?>

<?php echo $form->label($model,'rememberMe'); ?>

<?php echo $form->error($model,'rememberMe'); ?>



<?php echo CHtml::submitButton('Login'); ?>



<?php $this->endWidget(); ?>

</div><!-- form --> 

And Login model (protected/models/LoginFrom.php): 



 * LoginForm class.

 * LoginForm is the data structure for keeping

 * user login form data. It is used by the 'login' action of 'SiteController'.


class LoginForm extends CFormModel


public $username;

public $password;

public $rememberMe;

private $_identity;



* Declares the validation rules.

* The rules state that username and password are required,

* and password needs to be authenticated.


public function rules()


return array(

// username and password are required

array('username, password', 'required'),

// rememberMe needs to be a boolean

array('rememberMe', 'boolean'),

// password needs to be authenticated

array('password', 'authenticate'),





* Declares attribute labels.


public function attributeLabels()


return array(

'rememberMe'=>'Remember me next time',





* Authenticates the password.

* This is the 'authenticate' validator as declared in rules().


public function authenticate($attribute,$params)




$this->_identity=new UserIdentity($this->username,$this->password);


$this->addError('password','Incorrect username or password.');





* Logs in the user using the given username and password in the model.

* @return boolean whether login is successful


public function login()




$this->_identity=new UserIdentity($this->username,$this->password);





$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days


return true;



return false;



posted by Roopz on January 6, 2014

Multiple Configuration File Environments

This is very convenient way for those who use Subversion / Git and any Continuous Integration softwares. I am using Subversion for code versioning and Atlassian Bamboo for release management. 

1. Taking out environmental configurations, such as components->fixture, components->log, components->db and put them under protected/config/ as dev.env.php, demo.env.php, live.env.php: 



return array(

















      'connectionString' => 'mysql:host=localhost;dbname=your_dbname',

      'emulatePrepare' => true,


      'username' => 'your_username',

      'password' => 'your_password',


      'charset' => 'utf8',

      'tablePrefix' => '',







return array(

















      'connectionString' => 'mysql:host=localhost;dbname=your_dbdemo',

      'emulatePrepare' => true,


      'username' => 'your_demo',

      'password' => 'your_pass', 

      'charset' => 'utf8',

      'tablePrefix' => '',







return array(




      'connectionString' => 'mysql:host=localhost;dbname=your_dblive',

      'emulatePrepare' => true,


      'username' => 'your_live',

      'password' => 'y0uR_pAsS',


      'charset' => 'utf8',

      'tablePrefix' => '', 





2. Now in main.php, make "return array(" into "$config = array(" and in the end of the file:



if (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR.'live.php'))

  $config = CMap::mergeArray($config, require(dirname(__FILE__).'/live.php'));


elseif (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR.'demo.php'))

  $config = CMap::mergeArray($config, require(dirname(__FILE__).'/demo.php'));


elseif (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR.'dev.php'))

  $config = CMap::mergeArray($config, require(dirname(__FILE__).'/dev.php')); 

return $config;  

3. Make a copy of dev.env.php into dev.php in dev environment, demo.env.php into demo.php in demo environment, live.env.php into live.php in live environment. Now I don't have to worry about overwriting config files and easier to deploy for others now!

posted by Roopz on April 18, 2013

Layouts in Yii


There are many confusions regarding what is happening behind the scenes when you render a view.

If we take a look at the blog demo we have 3 major parts of our view rendering and they are:

1) The layouts/column1 and column2 that look like (column1.php and column2.php):


2) We have layouts/main

widget('zii.widgets.CBreadcrumbs', array('links'=>$this->breadcrumbs,)); 

3) and the view that we render , for example site/contact

$this->pageTitle=Yii::app()->name . ' - Contact Us';
$this-> breadcrumbs=array('Contact');
Contact Us

The call to the view rendering in the contact looks like the following:-

* Displays the contact page
public function actionContact()
$model=new ContactForm;
//some form code was here...
The common questions and confusions we will address: 

1) Why if I pass the contact some $test variable like $this->render('contact',array('model'=>$model,'test' => 123)); and I echo it in the layout with echo $test, I get error 500 undefind variable error?

2) I didn't pass any $content variable so what is doing inside the beginContent tags of column1.php ?

3) Why does the layouts/main. php have

I didn't pass such variable...

4) Why do both column1.php and main.php echo the $content ?

5) Why does setting the title inside contact.php change the variable $this->title in main.php?

/* in contact.php
$this->pageTitle=Yii::app()->name . ' - Contact Us';

And the main confusion:
6) What is called before what? What the heck is going on there ? ;-)

Diving in the source code 
You have two options:
1) You can accept the rules and follow them without understanding
2) You can understand and follow the rules...

If you choose number 1, tutorial is over for you ;-) But if you really want to learn and understand, let's dive together...

Every good IDE has the ability to go directly to the function by pressing ctrl and the function name...
So lets go to SiteController.php, to the actionContact and press the render word at this line:

$this->render('contact',array('model'=> $model));

After pressing you will find yourself inside yii/web/CController.php on line 775

public function render($view,$data=null,$return=false) 
        $this->afterRender($view,$output); $output=$this->processOutput($output); 
        if($return) return $output; else echo $output; 
The rendering is starting with a call to beforeRender, This is a preprocessing, if we are talking about the blog demo, no preprocessing there, so it just returns true...

protected function beforeRender($view)
return true;

After we got true, we can continue ...

We have,


So our 'contact' view is rendered partially, with third parameter as true, this means that the result is not echoed to the page, it is captured and passed to the $output variable...

At this stage the contact page is rendered, all the $data it got (the variable array) is passed to the view was processed

After this, if a layout is defined

if(($layoutFile=$this->getLayoutFile($this->layout))!==false) $output=$this->renderFile($layoutFile,array('content'=>$output),true);
we pass the $output we captured from the contact.php file, and pass it as $content to our layout file column1.php

Also this time the third parameter is true, meaning we done echo the output, we capture it and pass to $output variable (at this point the view output is overwritten, we don't need it any more cause we passed it to the view and it processed).

After this the afterRender called, and the processOutput, it's role is to insert all the javascript css etc. we registered as client scripts etc.

Time for answers 
After we followed all the life cycle of the render method, we can answer to all the questions...

1) why if I pass to the contact some $test variable like $this->render('contact',array('model'=>$model,'test' => 123)); And I echo it in the layout with echo $test, I get error 500 undefind variable error?

Answer: Because the parameters we pass to the $this->render method, are processed in the view file , in this example contact.php, and then we pass to the layout the generated view, and the variable $test is out of the scope for hte layout. What to do if you need it? you can use the Yii registry(params), or you can define some class field, or consider creating widget ... (depends on the task)

2) I dont passed any $content variable so what is

Inside the beginContent tags inside column1.php ? 

Answer: the captured view is passed to the layout as content parameter

3) Why the layouts/main.php has

Don't passed such variable...


All what between beginContent and endContent, is captured and passed to the layouts/main as content variable...

4) Why both column1.php and main.php echo the $content ?

Answer: If you understood answers to 1-3, you know the answer for this one... they are not the same, and don't have the same value

5) why if I change inside contant.php the title, it changes the main.php $this->title variable ?

/* in contact.php $this->pageTitle=Yii::app()->name . ' - Contact Us'; */

as we saw, the contact.php is rendered before the layout, so every field( aka class parameters), you change from the view file (contact.php) will effect the layout because it rendered after...

And the main confusion:
6) what is called before what? what the heck is going on there ? ;-)

contact.php (passed as content)-> column1.php (passed as content)-> main.php

That's it, now you pro in layouts ;-)
posted by Roopz on April 29, 2013

Read Posts From Rss Feed in Yii

We know ZEND has a very good Library for Playing woth RSS Feeds.

Here i am using Zend Framework with Yii.

You can download the ZEND framework from here

Recently i had worked with RSS Feed reading and storing the data to DB.

This functionalities are carried out using a cron scripts. So i have written the code as Cron-command.

What this cron command will do ?

This cron command will be executed preiodically (For example - once in a minute - we can set this value in our server). And each time cron script will check Feed URL (Where the feeds will get updated actually - This will be another end - Writing RSS Feeds :) ) and if there any updates, it will write the data informations to the DB (The data will be in XML format). Then these db data can be used to show anywhere in the website as a news feed or news updates.

You can see all the ZEND library classes and methods for consuming RSS feeds here. Its easy Right ?

Now we have Libary and methods to read/write RSS feed from ZEND. Whats next ?

Next we will Include this ZEND framework in our Yii Application. Its very easy to integrate a 3rd party application in Yii.

Integrating third party Applications in Yii

1. Create a folder called /vendors inside /protected folder.







Copy the "Zend" framwork folder inside "vendors" folder.


Then add the following line on config/main..php


'aliases' => array(
            'Zend' => realpath(__DIR__.'/../vendors/Zend/'),

Next write a cron command to read RSS feeds.

class ReadFeedCommand extends CConsoleCommand
    public function run($args)
        $model=new RssSourceItem;
        $modelSource = new RssFeedSource;
        $source = $modelSource->findAll(array('condition'=>'status=1'));
        foreach ($source as $rssSource) {
            /* Uncomment the following line if AJAX validation is needed
            $channel = Zend\Feed\Reader\Reader::import($rssSource->url);         
            foreach ($channel as $item) 
                $model->rss_feed_source_id = $rssSource->id;
                $model->title = $item->getTitle();
                $model->link = $item->getLink();
                $model->image = $item->getLink();
                $publishDate = $item->getDateModified();
                $i = 0;
                foreach ($publishDate as $object) 
                    $dateTime[$i] = $object;
                $model->publish_date = $dateTime[0]." ".$dateTime[2];
                $model->rss_date = $model->publish_date;
                $model->description = $item->getDescription();
                    echo "Feed Read Successfull";
            echo "Sorry...! Feed Read Fail";
$channel = Zend\Feed\Reader\Reader::import($rssSource->url);

The above line of code will retrieve all the feed data. Its too easy right ?

Thats all.

Enjoy RSS feed Read. :).

Feel free to contact me any time if you have any questions.

posted by Roopz on April 26, 2013

Fullcalendar and Yii

Downlaod the Full clander from

And iclude the following 

<link href='../static/libs/fullcalendar/fullcalendar.css' rel='stylesheet' />

<link href='../static/libs/fullcalendar/fullcalendar.print.css' rel='stylesheet' media='print' />

<script src='../static/libs/jquery/jquery-1.9.1.min.js'></script>

<script src='../static/libs/jquery/jquery-ui-1.10.2.custom.min.js'></script>

<script src='../static/libs/fullcalendar/fullcalendar.min.js'></script>

Sample View/Config 

$(document).ready(function() {
        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();
        var calendar = $('#calendar').fullCalendar({header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            selectable: true,
            selectHelper: true,
            select: function(start, end, allDay) {
                var title = prompt('Blocking For - Customer Details');
                if (title) {
                            title: title,
                            start: start,
                            end: end,
                            allDay: allDay
                        true // make the event "stick"
                start = mySqlDateConvertion(start); //JS CALL           
            //editable: true,
            events: [
                    id: 999,
                    title: 'Repeating Event',
                    start: new Date(y, m, d-3, 16, 0),
                    allDay: false

Set your CSS: Dont forget to set your html properties :)

body {
        margin-top: 40px;
        text-align: center;
        font-size: 14px;
        font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
    #calendar {
        width: 900px;
        margin: 0 auto;
posted by Roopz on April 25, 2013


EJS provides a lot of flexibility for using JavaScript templates. This article documents EJS's template API.

EJS is typically used by loading a template and rendering it with data.

Loading a template

Load a template by creating a new EJS template. Templates are cached by default.


template=new EJS({url:'/mytemplate.ejs'})

options is a hash that can include the following attributes:

  • url {string} - loads a template from a file
  • text {string} - uses the provided text as the template
  • element {string or element} - loads a template from the innerHTML or value of the element.

type {string} (optional) - '<' or '[', default is '<', except for loading a template from an element.

  • name {string} (optional) - an optional name that is used for caching. This defaults to the element ID or URL provided.
  • cache {boolean} (optional) - defaults to true. True if you want to enable caching of templates, false if otherwise.



There are 2 ways to render a template. The first method, render, simply returns text. Other method, update, is used to update the inner HTML of an element.


html =new EJS({url:'/template.ejs'}).render(data)

update(element, url_or_data)

Updates an element with the result of the template.


element {string or element} - the element you want updated

url_or_data - can be one of the following:

{null} - returns a function that takes an object as its first argument. That object will be used to render the template and update the element.

{string} - The string is used as a url to perform an AJAX request. The data returned from the ajax request is used to render the template and update the element.

{object} - Data used to render the template and update the element.


f =new EJS({url:'/mytemplate.ejs'}).update('my_element')
new EJS({url:'/mytemplate.ejs'}).update('my_element','/data.json')
new EJS({url:'/mytemplate.ejs'}).update('my_element',{supplies:['mop']})
posted by Roopz on April 20, 2013

Virtual Host in Apche

I wanted to play with Yii on my Ubuntu desktop today, and I had a little trouble setting Apache up (I didn’t remember my exact setup that I had on my laptop, which is in the shop). I was in the mood to write a tutorial, so I figured I would, well, write a tutorial.

If you run Ubuntu and you like to work on a website locally, it’s pretty useful to set up a virtual host for your new project. That way, you can have a local (just on your computer) top-level URL, which can be useful for certain apps that don’t like to be installed in a directory.

First, open up /etc/hosts. You will need to be sudo to do this (i.e. sudo vim /etc/hosts would work nicely.) Add these lines:

# Look at me, I'm making a virtual host!

This will reroute all requests to to, which should be your Ubuntu machine (AKA localhost).

Now, we need to make sure your web server knows what to serve when you request that host. I’m giving directions for Apache; I’m the procedure is similar for other servers.

First, make sure Apache is installed. You may also want PHP and MySQL installed. Run this command to install them:

sudo apt-get install apache2 php5 php5-mysql libapache2-mod-php5

Now if you go to you should see a page that says “It works!”. This is good. Now we can add virtual hosts.

Go to /var/www/ in your terminal. Run sudo mkdir myfakedomain to make a directory where your virtual host’s files will be. Then run sudo chown tavish:tavish myfakedomain to allow Tavish to read/write to that directory (switch tavish with your username).

Next, go to /etc/apache2. There is a directory called sites-available. Make a file there called myfakedomain. This will hold your Apache configuration for your virtual host. Here is an example file:

DocumentRoot /home/roopz/public_html/yiioverflow
Options Indexes FollowSymLinks MultiViews
AllowOverride All
DocumentRoot /home/roopz/public_html/Vaycay
Options Indexes FollowSymLinks MultiViews
AllowOverride All

Once you’ve saved that, run sudo a2ensite myfakedomain to add the site to Apache’s sites-enabled list and 

sudo /etc/init.d/apache2 restart  to restart Apache. will now point to your new virtual host. Add files to/var/www/ and you should be able to access them.

Let me know if you have any troubles.

posted by Roopz on April 20, 2013

How to use EJS in Yii ?

EJS cleans the HTML out of your JavaScript with client side templates. After EJS gets its rubber gloves on dirty code, you'll feel organized and uncluttered.

Setup EJS in Yii

1. Installation

Download the EJS from

$baseUrl = Yii::app()->baseUrl;
     $cs = Yii::app()->getClientScript();

Then use your EJS templates as follows

$('#messageboxouter').html(new EJS({url: host+'/static/ejsTemplate/messageList.ejs'}).render(result));

The EJS template with data passed as "result" in json format will be write into the html tag with ID "messageboxouter". Enjoy working with EJS :)