Wednesday 28 August 2013

Dynamic state city dropdown selection in Yii Framework

Here is the tutorial to select city from state id dynamically by using ajax in Yii Framework in 3 easy steps

1) Fetch all state name and state id from "State" table and show it in dropdown field

<?php 
$stateList = CHtml::listData(State::model()->findAll(array('order' => 'name')), 'state_id', 'name');
        echo $form->dropDownList($model, 'state_id', $stateList, array(
            'ajax' => array(
                'type' => 'POST', //request type
                'url' => CController::createUrl('ajax/getCities'), //url to call.                
                'update' => '#Address_city_id', //selector to update   
                'data' => array('state_id' => 'js:this.value'),
        )));
?>

Here I have added the 'ajax' array in dropdownlist field where:

- type is type of request i.e. POST/GET

- url is controller and action url to call (Here I have called the AjaxController's getCities() method)

- update is the selector to update i.e. city dropdownlist id

- data is state_id to send request to particular controller/action

This will generate the following HTML output:

<select id="Address_state_id" name="Address[state_id]">
<option value="1">Andaman & Nicobar</option>
<option value="2">Andhra Pradesh</option>
<option value="3">Arunachal Pradesh</option>
.
.
</select>

Here "value" field contains the state id and option name as state names

2) Create city dropdown field

<?php
echo $form->dropDownList($model, 'city_id');
?>

This will generate the following HTML output:

<select id="Address_city_id" name="Address[city_id]">
<option value="1">Kolhapur</option>
<option value="2">Ahmednagar</option>
.
.
</select>

3) In controller i.e AjaxController -> actionGetCities() method

<?php
class AjaxController extends Controller {

    public function actionGetCities() {        
    //Fetch all city name and id from state_id
        $data = City::model()->findAll('state_id=:id', array(':id' => (int) $_POST['state_id']));        
    //Passing city id and city name to list data which generates the data suitable for list-based HTML elements
        $data = CHtml::listData($data, 'city_id', 'name');
    //CHtml::tag which generates an HTML element
        foreach ($data as $value => $name) {            
            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
    }
}
?>

Thats it! Hope this will help you.

Sunday 4 August 2013

Shell script to search and replace number of string(s) or text(s) from file under its directory and subdirectory using Sed editor

Sometimes while working on project you may need to do few changes in string(s)/text(s) on your working files like comments blocks, file headers, date etc. Following Shell script will help you to replace strings and texts under its directory and subdirectory using Sed editor. But before implementing this you must need to aware with Sed editor and how to use it.

Introduction to Sed

Sed is a special editor for modifying files automatically. If you want to write a program to make changes in a file, sed is the tool to use. To know more about its syntax, commands and how to use it please check this link : http://www.grymoire.com/Unix/Sed.html or just google "Sed".


Example

#!/bin/sh 
 # Shell script to search and replace number of string(s) or text(s) from file under its directory and subdirectory.

MYDIR="your_directory_name/"

show_files()
{
 if !(test -d "$1") 
    then return;
 fi

cd "$1"
 echo "$1"; #Show Directory name 

 for i in *
 do
 if test -d "$i" #if directory
    then 
        show_files "$i" #recursively list files
        cd ..
 else
        sed -i 's/HelloWorld/Welcome/g;' $i;
        sed -i 's/refer to http:\/\/www.oldsite.com/contact http:\/\/www.newsite.com/g;' $i;
        sed -i 's/HelloWorld/Welcome/g;' $i;
        sed -i 's/Helloworld/Welcome/g;' $i;
        sed -i 's/2007\-2013/2013/g;' $i
        sed -i 's/@oldsite/@newsite/g;' $i;
        sed -i 's/oldprefix_/newprefix_/g;' $i;
        echo "$i"; #Display File name
 fi
 done
}

if [ $# -eq 0 ]
then show_files "$MYDIR"
exit 0
fi

for i in $*
do
 MYDIR="$1"  
 show_files "$MYDIR"
 shift 1 #To read next directory/file name
done

Thanks. Hope it'll help you.

Activate Gii code generator for frontend in YiiBoilerPlate

1) First check the directory "runtime" exist or not in frontend folder if not then create it.
2) Go to folder frontend/config
3) Open file main.php
4) Add the following line in array()

'modules' => array(
                'gii' => array(
                    'class' => 'system.gii.GiiModule',
                    'password' => '<your_gii_password>',
                    'generatorPaths' => array(
                        'bootstrap.gii'
                    )
                ),
            ),

i.e.

return CMap::mergeArray(
                array(
            // @see http://www.yiiframework.com/doc/api/1.1/CApplication#basePath-detail
            'basePath' => 'frontend',
            // set parameters
            'params' => $params,
            // preload components required before running applications
            // @see http://www.yiiframework.com/doc/api/1.1/CModule#preload-detail
            'preload' => array('log'),
            // @see http://www.yiiframework.com/doc/api/1.1/CApplication#language-detail
            'language' => 'en',
            // uncomment if a theme is used
            /* 'theme' => '', */
            // setup import paths aliases
            // @see http://www.yiiframework.com/doc/api/1.1/YiiBase#import-detail
            'import' => array(
                'common.components.*',
                'common.extensions.*',
                'common.models.*',
                // uncomment if behaviors are required
                // you can also import a specific one
                /* 'common.extensions.behaviors.*', */
                // uncomment if validators on common folder are required
                /* 'common.extensions.validators.*', */
                'application.components.*',
                'application.controllers.*',
                'application.models.*'
            ),
            /* uncomment and set if required */
            // @see http://www.yiiframework.com/doc/api/1.1/CModule#setModules-detail
            /* 'modules' => array(), */
            'components' => array(
                'errorHandler' => array(
                    // @see http://www.yiiframework.com/doc/api/1.1/CErrorHandler#errorAction-detail
                    'errorAction' => 'site/error'
                ),
                'db' => array(
                    'connectionString' => $params['db.connectionString'],
                    'username' => $params['db.username'],
                    'password' => $params['db.password'],
                    'schemaCachingDuration' => YII_DEBUG ? 0 : 86400000, // 1000 days
                    'enableParamLogging' => YII_DEBUG,
                    'charset' => 'utf8'
                ),
                'urlManager' => array(
                    'urlFormat' => 'path',
                    'showScriptName' => false,
                    'urlSuffix' => '/',
                    'rules' => $params['url.rules']
                ),
            /* make sure you have your cache set correctly before uncommenting */
            /* 'cache' => $params['cache.core'], */
            /* 'contentCache' => $params['cache.content'] */
            ),
            /* uncomment and set if required */
// @see http://www.yiiframework.com/doc/api/1.1/CModule#setModules-detail
            'modules' => array(
                => array(
                    'class' => 'system.gii.GiiModule',
                    'password' => 'admin',
                    'generatorPaths' => array(
                        'bootstrap.gii'
                    )
                ),
            ),
                ), CMap::mergeArray($mainEnvConfiguration, $mainLocalConfiguration)
);

5) Check it by accessing http://your_domain/gii

Thanks

Fix Gii Error 403 You are not allowed to access this page (Yii Framework)

After configuring Yii framework or YiiBoilerPlate you might be getting following error while accessing Gii code generator:

Error 403
You are not allowed to access this page:

This can be happen in your localhost or remote host wherever you are developing your web app. To resolve this you need to add your development computer’s IP address to your main.php file as follows:

In Yii Framework

1) Go to yourwebapp/protected/config folder.
2) Open main.php file.
3) Add the following line in main.php in "gii" array as follows:

'gii' => array(
            'class' => 'system.gii.GiiModule',
            'password' => 'admin',
            'ipFilters' => array('127.0.0.1', $_SERVER['REMOTE_ADDR'])
),

YiiBoilerPlate

And if you are using YiiBoilerPlate then go to yourwebapp/backend (or frontend)/config/main.php file and add the same line in Gii array.