Showing posts with label YII Framework. Show all posts
Showing posts with label YII Framework. Show all posts

Thursday, July 5, 2012

Getting action/controller/module name in Yii

Some times we need to know the current controller/module/action name in our application, Yii provides the default methods to accomplish the tasks.

To get a controller name
Yii::app()->controller->id //or
$this->id  here $this refers to current controller 

To get method/action name
You can get action name in controller

To get module name

Tuesday, July 3, 2012

All about validation in Yii - PART1

Validation in YII (Server side & Client Side)- PART 1

Yii support server side validation &  client side validation and it has wide range of built in validators, here we are going to see the each and every points about validation features that Yii provide.

Declaring Validation Rules

We specify the validation rules in Model class through the rules() method which should return an array of rule configurations. validators are called in order if we specified more than one validator for attribute
rules() method is a default method that triggers yii validation by using rules() method while validate() called. validate() function triggered automatically while we call $model->save() orcall $model->validate().

Validation rule syntax

array('AttributeList', 'Validator', 'on'=>'ScenarioList'...), 

Here AttributeList defines the list of model attributes, if more than one attribute it should be separated by comma.
Validator defines type of validation to be done yii provides the built in validators for email, url and so on refer table 1 for built in validators.
ScenarioList tells on which scenario the validation rule should fire, more than one scenario will be separated by comma.

Adding validations to model

        public function rules(){
        return array('username','required');

the above validation rule tells the yii to validate username fields to be mandatory through required validator. we apply same validation rule for  more than one field, by separating them with comma
        public function rules(){
        return array('username,password','required');

in the above example we set username and password field to be mandatory and we can apply more than validation to same attribute
        public function rules(){
        return array(
        array('username','length','min'=>3, 'max'=>12);        

Above example tells yii to validate username attribute length should have 3-12 and it is required.

Yii triggers validation when we call $model->validate(); or $model->save(); While saving records validation automatically called by default, if validation should be avoided in save methods $model->save(false); //which cancels validation

Clear steps

Model Finally model looks likes this
        class LoginForm extends CFormModel
        public $username;
        public $password;        
        public function rules()
        return array(
        array('username, password', 'required'),
        array('username','length','min'=>3, 'max'=>12);

$model = new Users();

Trigger Validation

to get particular field validation error, Yii add these statements to view by default why we scaffolding our code.

<?php echo $form->error($model, 'username'); ?> 
To get error summary for all fields
<?php echo $form->errorSummary($model); ?>

Contd.. on PART II

Handle JSON Response in Yii

Convert array to json data
convert array data to json using json_encode() function use the below example, $this->layout=false makes yii to stop rendering layout for this action.

public function actionJsonTest(){
header('Content-type: application/json');
echo json_encode($arr);

Convert model data to json 
convert your existing model data to json
  header('Content-type: application/json');
  $post = Post::model()->findByPK((int)$id);
  echo CJSON::encode($post);

Convert model data with relations to json 
use this behaviour Converts Model Attributes and its Relations to a JSON

Shopping cart in yii

Yii based shopping cart

Here is my compilation but i couldn't find any full fledged e-commerce framework. this will help some one to create complete e-commerce application.


Shopping cart component
Yii based ecommerce site but not open source
Shopping cart
Yii Cart
A tiny shopping cart script that supports batch products additions

Tuesday, June 26, 2012

Handling Scripts and CSS in Yii Framework

Handling Scripts and CSS in Yii Framework

Yii provide CClientScript to manage the scripts and css files in Yii.

Registering Core scripts that comes with Yii

To register the core jquery library that comes with yii, use the following methods.

Yii::app()->clientScript->registerCoreScript( 'jquery.ui' );
//We need to pre-render the jquery.yiiactiveform.js on the view where we are going to place the AJAX functionality

The above statement register the Jquery library and jquery ui, if YII_DEBUG is false then yii will register minimized version of Jquery & Jquery UI library.

To register inline scripts and css files
Yii::app()->clientScript->registerScript('unique scriptname','js code',position)

Yii::app()->clientScript->registerCss('unique css','csscode','media=>print/handheld/screen')

Script Positions

CClientScript::POS_HEAD : the script is inserted in the head section right before the title element. .
CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section.
CClientScript::POS_END : the script is inserted at the end of the body section.
CClientScript::POS_LOAD : the script is inserted in the window.onload() function.
CClientScript::POS_READY : the script is inserted in the jQuery's ready function.

so if you use,
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl . '/script/test.js',CClientScript::POS_END);
then the script will be inserted to the body section

To register external scripts and css files

Yii::app()->clientScript->registerCssFile($yourscript_asset. '/test.css');
Yii::app()->clientScript->registerScriptFile($yourscript_asset. '/test.js')

Publishing scripts to assets directory

Asset manager in brief

CAssetManager is a Web application component that manages private files (called assets) and makes them accessible by Web clients. It achieves this goal by copying assets to a Web-accessible directory and returns the corresponding URL for accessing them.
you can compress and minify and otherwise process your assets with the asset publishing system, and it makes it easier to host your JS and CSS on a CDN since it's separate from your codebase.With assets, a component can be used easily without worrying about what files to be copied to public directories and what their URLs are
Consider a scenario, if we have two scripts which is located in scripts/testscript, the directory has two files namely test.js and test.css. We are going to publish it to asset and then we consume that files from asset directory, here is the snippet
$yourscript_asset= Yii::app()->assetManager->publish(Yii::app()->basePath . '/scripts/testscript /');

//Register JS and CSS files        
Yii::app()->clientScript->registerCssFile($yourscript_asset. '/test.css');
Yii::app()->clientScript->registerScriptFile($yourscript_asset. '/test.js');


Load files from google server

Cleans all registered scripts before any script register

Cleans all registered scripts.

Prevent loading jquery files

Yii::app()->clientScript->scriptMap['jquery.js'] = false;
//or if more than one script to be prevent from registering

Avoiding scripts download on AJAX renderPartial request

Suppose we created a function to display the AJAX active form and its contents are returned by a call to a controller’s action that will partially render a view.
// Just before rendering the view that
// has our activeform
Yii::app()->clientScript->corePackages = array();
Now controller doesn't return script files.
It is very important that we set corePackages to array() instead of null, as setting it to null will make CClientScript to reload the packages.php file (located in framework/web/js/) and we won’t stop the duplication of the script.

Sunday, June 17, 2012

Fixing The CSRF token could not be verified

"The CSRF token could not be verified", if you get this message while using YII Framework. the issue can happen in
1.You are not using CHtml Form widget
2.You are not using CActiveFormWidget
3.You are using cusom ajax handlers

If you are using CHtml Form widget or CActiveForm widget the Yii Framework automatically validate CSRF token, if we using custom form or custom jquery ajax methods we should pass YII_CSRF_TOKEN to POST request, this may solve the above issue

$csrfToken = Yii::app()->request->csrfToken; // 
will return the csrf token associated with the context, you can now use that csr token to pass in jquery ajax functions

to check csrfvalidation enabled in application use the following method to get status

Getting CSRF Token from javascript

open source projects built with yii

List of open source projects built with yii, this is the partial list, if you know others let me know.

 Hamster  Forum software
 Celestic Open source project manager
Zurmo CRM
Customer Relationship Management – CRM
X2 Engine
Customer Relationship Management – CRM
Bug tracker application
Question and answer site like stackoverflow
Flexica CMS
Content Management System
Phundament CMS
Content Management System

Content Management System
Content Management System

Web 2.0 CMS

Content Management System

Content Management System

Content Management System


blog web application
Simple Project Manager / Bug Tracker

Wiki application/module
Open Real Estate Used to built websites of real estate agencies and realtors.

Monday, August 8, 2011

How to minify Javascript, CSS files automatically in YII Framework

We are going to reduce the HTTP calls for resources files by merging several resources files into a single (or more) files, so that the application load faster. E Client Script can automatically detect the required list of files, and generate a unique filename hash, so boldly ease of use.

CSS Files:

CSS files are merged based on there media attribute, background images with a relative path in file can also be displayed correctly.

Script files:

Script files are merged based on their position, If you use the 'CClientScript::POS_HEAD' you will end up with a single file for all the script files you've used on that page.

If you use 'CClientScript::POS_HEAD' and 'CClientScript::POS_END' for example then you'll end up with two files for each page on that request, Since those resources are located in different positions.

Add the following code to components array in protected/config/main.php

Add to configuration:
First you have to download EClientScript extension

 'clientScript' => array(
            'class' => 'ext.minify.EClientScript',
            'combineScriptFiles' => true,
            'combineCssFiles' => true,
            'optimizeCssFiles' => true,
            'optimizeScriptFiles' => false,

Then you'd use the regular 'registerScriptFile' & 'registerCssFile' methods as normal and the files will be combined automatically

Enable GZIP in YII Application

Just add the following lines to protected/config/main.php,

add the below 2 lines after   'preload' => array('log'),

'onBeginRequest' => create_function('$event', 'return ob_start("ob_gzhandler");'),
'onEndRequest' => create_function('$event', 'return ob_end_flush();'),

Friday, August 5, 2011

Module based login in YII Framework

Module based login

What is module?

From YII Framework documentation

 "A module is a self-contained software unit that consists of models, views, controllers and other supporting components. In many aspects, a module resembles to an application. The main difference is that a module cannot be deployed alone and it must reside inside of an application. Users can access the controllers in a module like they do with normal application controllers.

Modules are useful in several scenarios. For a large-scale application, we may divide it into several modules, each being developed and maintained separately. Some commonly used features, such as user management, comment management, may be developed in terms of modules so that they can be reused easily in future projects."

For example
admin users   = > index.php?r=admin/default/login
general users => index.php?r=user/default/login

To add module based login to a site without using RBAC, please follow these guidelines.
Consider the situation where we want to add 3 types of login in a site: customer, dealer, and admin.

Start by generating three modules using GII. (To do this, please refer to this guide for module generation

Step 1
Copy the UserIdentity component to the module/components folder for each module. We will validate each module against its table. For example, customer validation is done using customer table, and admin validation against the admin table

For each module, change its UserIdentity authenticate() function to perform the appropriate validation.

Step 2
For each module, add the following lines to its main page. For example, for the Customer module, add to Customer/CustomerModule.php Add the following lines to init():

'errorHandler' => array(
'errorAction' => 'customer/default/error'),
'user' => array(
'class' => 'CWebUser',             
'loginUrl' => Yii::app()->createUrl('customer/default/login'),


Step 3
Create the login/logout action in each module's DefaultController.
For example, for the Customer module:
Create the actionLogin() in Customer/controllers/DefaultController.php.
Also, create actionLogout() as follows:

public function actionLogout() {

Point sub-domain to module
This tips from the forum URL Subdomain to module
There is a feature called "Parameterizing Hostnames" (described on this pages). add the following lines to main.php

'components' => array(
'urlManager' => array(
'rules' => array(
'' => 'customer/default/index',
'' => 'customer/default/login',
So "customer/default/index" refers to the module "customer" with controller "default" and action "index".

Redirect to respective module login, if user not logged in to a particular model
add following code to customer module CustomerModule.php in beforeControllerAction

do the same for other module
in SiteController's site/login method
public function actionLogin() {

Another method(Recommended)
Redirect to respective module login, if user not logged in to a particular model
add following code to customer module CustomerModule.php
public function beforeControllerAction($controller, $action) {
if (parent::beforeControllerAction($controller, $action)) {
// this method is called before any module controller action is performed
// you may place customized code here
$route = $controller->id . '/' . $action->id;
// echo $route;
$publicPages = array(
if (Yii::app()->user->isGuest && !in_array($route, $publicPages)){            
return true;
return false;

do the same for other module
Thanks to ricardograna for sharing some configurations