Thursday, July 5, 2012

Using modules in Yii

What is modules?
Module is separate piece of application that can have Models, Controller,Views, modules are placed in protected/modules directory. We can define login system for modules.Module cannot be deployed alone it needs application to run.
  • Modules can be nested in unlimited levels
  • Modules may have separate login system

Application directory structure

 protected
   /commands
   /components
   /config
   /controllers
   /models
   /modules
       /admin       
       /user
       /agent

We have three modules placed under modules directory namely admin,user,agent. if we look in to the module directory structure we can find many files and folders similar to application.

   /modules
       /admin    
          AdminModule.php
          components/                
          controllers/                       
               DefaultController.php   
          extensions/                      
          models/                    
         views/                     
         layouts/               
         default/              
             index.php            


Why we have to use modules?
In large scale application we may divide our application in to many modules so that they can be resused later and it makes application maintenance easier.

Creating a Modules
Enable Gii in application config, open Gii generator using yourapplication/?r=gii/default/login in browser addresbar, then type your password,
'modules' => array(
        // uncomment the following to enable the Gii tool
        'gii' => array(
            'class' => 'system.gii.GiiModule',
            'password' => 'giitest',
        ),
         .......
click module generator enter your module name that's all yii will do the rest.
Gii module generator


Using Module
To use modules in our application, we have to configure it in application config file
'modules' => array(
        // uncomment the following to enable the Gii tool
        'gii' => array(
            'class' => 'system.gii.GiiModule',
            'password' => 'giitest',
        ),
        'user', //user module
        'admin', //admin module
        'agent', //agent module
    ),

Nested Module
Module can have any number of nested module.one module can contain another module previous module called parent module later module called child module so one can access child module action like. parentModuleID/childModuleID/controllerID/actionID
'modules'=>array(
    'module1'=>array(
        'modules'=>array(
            'module2',
            'module3'
        )
    )
)

 Sharing Models/Components/extensions to Modules

To share application's models/components/extensions to module, just import them using setImport function.

Here we are sharing models from user module, so admin and user model will use same model across application

class AdminModule extends CWebModule
{
 public function init()
 {
  // this method is called when the module is being created
  // you may place code here to customize the module or the application

  // import the module-level models and components
  $this->setImport(array(
   'admin.models.*',
   'admin.components.*',
   'user.models.Profile',      //sharing models from user module
   'user.models.TransactionHistory',
                        'agent.models.*',
  ));
               .....


Sharing Layouts to Modules

To share a main layout to module controller

class AdminController extends Controller
{ 
 public $layout='//layouts/admin';
...

the above statement uses admin template from protected/views/layouts/admin

// uses application views folder, refers to "protected/views/layouts"
/ uses module views folder refers to "protected/modules/module/views/layouts"

Creating Login system for Modules
Refer my previous article Module based login 


Pointing Subdomains to modules

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(
         'http://customer.example.com' => 'customer/default/index',
         'http://customer.example.com/login' => 'customer/default/login',
      ),
   ),
   ...
),

So "customer/default/index" refers to the module "customer" with controller "default" and action "index".>

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
Yii::app()->getController()->getId()
$this->id  here $this refers to current controller 

To get method/action name
Yii::app()->controller->action->id
You can get action name in controller
$this->action->id

To get module name
Yii::app()->controller->module->id
$this->module->id

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,password','required');
        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);
        );
        }  
        }
    



Controller
$model = new Users();

Trigger Validation
$model->validate();

View
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(){
$this->layout=false;
$arr=array('Fruits'=>array('apples','orange'),'Vegetables'=>array('beans','carrot'));
header('Content-type: application/json');
echo json_encode($arr);
Yii::app()->end();
}


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);
  Yii::app()->end();


Convert model data with relations to json 
use this behaviour Converts Model Attributes and its Relations to a JSON  http://www.yiiframework.com/extension/ejsonbehavior/

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.



yii-shop

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