Yii Validation Rules

Hi, it is very easy to apply data validation rules in Yii.

..
..
..
..
..
..

Write validation rules in the Model file. e.g.

public function rules() {
        return array(
         
        );
    }

1) Required Validation

array('name', 'required'),

2) Unique Record Validation

array('name', 'unique'),

3) Url Validation

array('website_url', 'url'),

4) Safe Data Validation

array('address','safe'),

5) Integer Validation

array('zip_code', 'numerical', 'integerOnly' => true),

6) Max Length Validation

array('name, contact_person', 'length', 'max' => 250),

7) Password Retype Validation

array('password', 'compare', 'compareAttribute'=>'password_repeat', 'on'=>'register'),

8) File Extension Validation

array('photo', 'file', 'types'=>'jpg, gif, png'),

So you can integrate different types of rules like this

public function rules() {
        return array(
            array('name', 'required'),
            array('name', 'unique'),
            array('company', 'numerical', 'integerOnly' => true),
            array('email_address', 'email'),
            array('website', 'url'),
            array('name, email_address, website', 'length', 'max' => 250),
            array('contact_number', 'length', 'max' => 100),
            array('id, name, email_address, contact_number, website, address, date, company', 'safe', 'on' => 'search'),
        );
}

Easy rollover image with jQuery

Rollover images are very popular in buttons, navigation bar and stylish image gallery. It is very easy to implemented using jQuery. Just follow below steps to make easy rollover image.




1) Make two images with _on, _off suffix.

2) Add class “rollover” on image

<img src="image_off.jpg"  class="rollover"  /> 

3) Paste below jQuery Code in the head section of the document.

<script>
//hover image        
$(document).ready(function() {
$("img.rollover").hover(
function() { this.src = this.src.replace("_off", "_on");
},
function() { this.src = this.src.replace("_on", "_off");
});
});
//customize jquery for preloading img
</script>

Dynamic Dropdown in Yii Framework

Hi, html select dropdown is very important in the html forms. This dropdown can be implemented in Yii manner in easy and effective way. Basically there can be two types of dropdown can be implemented, i) Static and ii) Dynamic. Static means that no database is implemented and dynamic means that it includes database and values are fetched from the database table.

Static Version

echo $form->dropDownList($user,'salutation',array('Mr'=>'Mr','Mrs'=>'Mrs', 'Ms'=>'Ms', 'Mdm'=>'Mdm', 'Dr'=>'Dr'));

Dynamic Version

echo CHtml::dropDownList('Entries[category]',$entry->category, CHtml::listData(Category::model()->findAll(), 'cat_id', 'cat_title'),array('empty'=>'--please select--','class'=>'select'));

Configuring Amazon S3 with Yii framework

Hi friends, i came with another useful article. It is about configuring amazon s3 with yii framework. As you know that amazon s3 is a very popular CDN so you can improve your website performance by using this technique in yii framework.

Requirements
1) Valid account of Amazons S3. You can go there to create account and create buckets(folders).
2) Yii framework.

Steps are given below
1) Download S3 extension for Yii from here or download latest version from the url http://www.yiiframework.com/extension/s3assetmanager/.

2) Extract the download folder and there will be 2 folders, i) components and ii) extensions. Move the content of components folder into protected/components and extensions into protected/extensions.

3) Open config/main.php and paste below code in ‘components’ section

               'cache'=>array(
		   'class' => 'system.caching.CFileCache',	
	       ),
	    
	       's3' => array(
		   'class' => 'ext.s3.ES3',
		   'aKey'=>'YOUR A KEY HERE', 
		   'sKey'=>'YOUR S KEY HERE',
	       ),
	       'assetManager' => array(
		   'class' => 'S3AssetManager',
		   'host' => 'your-bucket-name.s3.amazonaws.com', // changing this you can point to your CloudFront hostname
		   'bucket' => 'your-bucket-name',
		   'path' => 'assets', //or any other folder you want
	       ),

Note : Look at ‘class’ => ‘system.caching.CFileCache’, I used ‘CFileCache’ file cache class but ‘CMemCache’ class is recommended here. I don’t have memcache on my web server so i used CFileCache class.

4) Now, open your controller file and put below method.

    public function assets($file)
    {
	if(IS_LOCAL)
	{
	    return $file;
	}
	else
	{
	    return Yii::app()->assetManager->publish($file);
	}
    }

Note : I used this method because my internet connectivity is not good and i need local files to work on localhost. IS_LOCAL is a constant defined by me to check whether i am on localhost or on server. I added below code in index.php of the yii project.

if($_SERVER['HTTP_HOST']=="localhost:8888")
{
	define("IS_LOCAL",true);
}
else
{
    define("IS_LOCAL",false);
}

5) Everything is done, so you can now use the code into your project in below manner.

<img src="<?php echo $this->assets('images/test.jpg') ?>" />

Thanks for visiting my website. Please drop your comments to encourage me or tell me if you see any mistake in the article.

Selecting Records from one table depending on another table using CActiveDataProvider in Yii Framework

Hi friends, i came back with another simple tutorial. In this tutorial, i will show you that how to select records from one table depending on another table.

useful code Selecting Records from one table depending on another table using CActiveDataProvider in Yii Framework

Example ::

Let us suppose we have two tables

1) tbl_videos (Model = Videos) -> id, title, video_embed_code, is_active
Videos table has the records of videos collected from different sources (e.g. youtube)

2) tbl_votings (Model = Votings) -> id, video_id, vote_date
Votings table has the records of voting of the videos, i.e. user can give votes on any video and are stored into Votings table.

I hope, you are now familiar about the problem, now we proceed to find the solution.

Steps are ::

  1. Open the model Videos and add below code (a new rule in relations method)

    'videosvotings' => array(self::HAS_ONE, 'Votings', 'video_id'),

    it will look like this

    public function relations()
    {
        return array(
    	'videosvotings' => array(self::HAS_ONE, 'Votings', 'video_id'),
        );
    }
    
  2. Now open your view file in which CActiveDataProvider is used and write below code.

    $dataProvider = new CActiveDataProvider('Videos', array(
        'criteria'=>array(
    	'with'=>array('videosvotings'),
    	'condition'=>" is_active = 1 and WEEKOFYEAR(videosvotings.vote_date)=WEEKOFYEAR(NOW()) ",
        ),
        'pagination'=>array(
    	    'pageSize'=>10,
        ),
    ));
    

    it will select all videos on which users have given vote.

  3. Now $dataProvider variable contains all records of the table, we can use this variable to show records in different ways, i show the usage in CListView below.

     $this->widget('zii.widgets.CListView', array(
        'dataProvider'=>$dataProvider,
        'itemView'=>'_video_single',  	     
        'pager'        => array(
          'class'          => 'CLinkPager',
          'firstPageLabel' => '<<<',
          'prevPageLabel'  => ' < ',
          'nextPageLabel'  => ' > ',
          'lastPageLabel'  => '>>>',
          'header'=> '',				
          ),
         'pagerCssClass' => 'pagination',
    ));
    

    or we can use directly without using ClistView as below

    foreach($dataProvider->getData() as $data)
    {
      echo $data->title;
    }
    

Please encourage me to write new tutorials by providing your valuable comments.

Few Useful Small Codes in Yii Framework

Hi, I always struggled to fix small errors when i was new in Yii Framework. So i am writing a useful tutorial to summarize small code blocks in easy way so that you newbie can take help from my tutorial.

useful code Few Useful Small Codes in Yii Framework

Let us suppose we have a table tbl_videos and we created a model Videos of this table, then we can get records from this table in various ways.

  • Getting a single row from the table.

    $singleVideo = Videos::model()->findByPk($id);

    here $id is the id of the table tbl_videos

  • Getting all records from the table.

    $videos = Videos::model()->findAll();

  • Getting limited records from the table.

    $videos = Videos::model()->findAll(array("limit"=>2));

  • Getting records against some conditions.

    $videos = Videos::model()->findAllByAttributes(array("is_active"=>1));

    here is_active is a column name in the table
    you can use multiple conditions in array like this array(“is_active”=>1,”is_viewed”=>1)

  • Getting records against some conditions in a specific order.

    $videos = Videos::model()->findAllByAttributes(array("is_active"=>1),array("order"=>"id desc"));

    to get random records you can set array(“order”=>”rand()”)

  • Getting limited records against some conditions in a specific order.

    $videos = Videos::model()->findAllByAttributes(array("is_active"=>1),array("order"=>"id desc","limit"=>'3'));

  • At this stage we stored records in $videos variable, now we use below code to iterate the record one by one.

    foreach ($videos as $video)
    {
        echo $video->id."<br />";
        echo $video->title."<br />";
    }
    
  • Counting records:
    Similarly you can count records of the table in below ways.

    $countVideos = Videos::model()->count();
    $countVideos = Videos::model()->countByAttributes(array("is_active"=>1));
    $countVideos = count($videos);
    

  • Please provide your valuable comments if you see any error in above codes or have any suggestion.

    Sending email using SwiftMailer Extension in Yii Framework

    Hi, if you need a solid email script to send emails in Yii framework then you can use SwiftMailer Extension that is solid and super easy to implement. The main reason for me in choosing this extension is that native php mail function does not work for every type of server and has not file attachment system in easy way. So lets implement the extension.

    swift mail Sending email using SwiftMailer Extension in Yii Framework

    Steps are given below

    • Download working extension from here or you can download the latest version from here.
    • Unzip downloaded folder in protected/extension folder
    • Open protected/config/main.php file and add below code in import section
         'application.extensions.yii-mail.*',
      
    • Again in protected/config/main.php file and add below code in components section
      'mail' => array(
         'class' => 'application.extensions.yii-mail.YiiMail',		
         'viewPath' => 'application.views.mail',
         'logging' => true,
        'dryRun' => false
      ),
    • At this time we have included the extension successfully in our framework, so to use the extension open your controller file and add below code
          $message = new YiiMailMessage;		     		     		     
          $message->setBody($body, 'text/html');
          $message->subject = "Subject goes here";		     		     
          $message->addTo("enter the email address of the receiver");  //you can add multiple addTo for more than one receiver
          $message->from = "enter the email address for the sender";
          Yii::app()->mail->send($message);	
      
    • Its done :) you can test the script after uploading the script on your website.

    Tested on :

    Yii : 1.1.8
    SwiftMailer : 4.0.6

    Resources :

    http://techisworld.com/files/yii-mail.zip
    http://www.yiiframework.com/extension/mail/
    https://code.google.com/p/yii-mail/
    http://swiftmailer.org

    Please leave your valuable feedback/suggestions using below comment box.

    Apple Claims the domain name iPhone 5, Requests UN Agency to Close It

    iPhone 52 Apple Claims the domain name iPhone 5, Requests UN Agency to Close It

    Is Apple planning to officially name its succeeding generation of iPhone – iPhone 5? Though speculations about it are rife, a recent compliant that Apple has made with the World Intellectual Property Organization (WIPO) indicates so.

    The WIPO is an agency under the purview of the United Nations and it is the job of this agency to protect all intellectual properties. Providing protection against alleged cyber-squatting also falls within the authority of the World Intellectual Property Organization (WIPO). The complaint that Apple has filed with the World Intellectual Property Organization (WIPO) concerns the iphone5.com domain, as first reported by Fusible.

    The domain name of iphone5.com domain was registered way back in 2008 by an Australian based registrar. The iphone5.com domain presently hosts all message boards related to iPhones and advertisements of smartphones.

    After the news of the complaint filed by Apple became public, quite a few threads were initiated online. One such thread, which was started on Sunday afternoon, urges the iphone5.com domain visitors to actively prevent Apple from taking over the site. Some users are vehemently against the takeover and have even suggested measures like calling up the corporate of Apple, spamming their emails, blowing up their phones and calling up the Administration in order to drive home the point and prevent the takeover.

    Another thread is conducting a poll to see how people feel about Apple taking over the domain. Till now the votes are split 60-40 in the favor of Apple.

    Speculations about the design and features of the following generation of iPhones have been doing the rounds for quite a few weeks now and bloggers and iPhone fans have already started calling the next Apple iPhone the iPhone 5 though there is no official word on it.

    It is only when Apple makes an official statement about the next generation iPhone will all the speculations be put to rest.

    Setting MySql Timezone in YII Framework

    Hi, if you want to set any specific timezone in YII framework for mysql records then you can simply use below command before inserting or updating the model

    ..
    ..
    ..
    ..
    ..
    ..
    ..

    Yii::app()->getDb()->createCommand("SET time_zone='+08:00'")->execute(); 

    Example ::

    <?php 
    actionPost()
    { 
        Yii::app()->getDb()->createCommand("SET time_zone='+08:00'")->execute();
        $model = new Post();
        $model->postTime = new CDbExpression('NOW()');
        $model->save();
    }
    ?>
    

    In above code, +08:00 is the timezone for Singapore, you can change it to your required country’s timezone, you can find the list of all countries timezone here http://www.timeanddate.com/library/abbreviations/timezones

    You can show date in your desired format in CGridView as below

    array(
    'name'=>'added_on',       
    'value'=>'date("d-m-Y h:i A", strtotime($data->added_on))', //simple way
    'value'=>'Yii::app()->dateFormatter->format("d MMM y",strtotime($data->added_on))', //yii way
    'type'=>'raw',
    ),
    

    Renaming YII Module in few steps

    Hi, Its a headache to rename module in YII, so i am writing here few steps to rename it based on my experience.

    Suppose we have a module “Movies” and we want to rename it “Photos” then we can follow below steps

    Note :: Take backup of files and database before following the steps

    1) Rename database table name, eg. 
    tbl_movies
    to tbl_photos

    2) Rename controller and model file
    models/Movies.php to models/Photos.php and
    controllers/Movies.php to controllers/Photos.php

    3) Search and replace below texts of all files of the module in one shot using any text editor software such as dreamweaver, netbeans or eclipse etc. Use case sensitive search and replacing always.
    Movies to Photos
    MOVIES to PHOTOS
    movies to photos
    renaming files 150x150 Renaming YII Module in few steps

    its done :),

    You are not limited to rename only modules but you can change whole project by following above procedures.

    Please give your valuable feedback and tell me if i missed anything here.