Wednesday 25 December 2013

How to get file extension in PHP

In PHP there are many ways to exclude a file extension such as using substr() or RegEx etc. But to use pathinfo() is the better way to deal with this.

The pathinfo() function returns an array that contains information about a path. The following array elements are returned:

Array
(
[dirname] => /directory_name (Ex. Test)
[basename] => file name (Ex. mydoc.png)
[extension] => file extension (Ex. png)
)

It has two parameters: pathinfo(path,options);
path: filepath
options:
PATHINFO_DIRNAME - return only dirname
PATHINFO_BASENAME - return only basename
PATHINFO_EXTENSION - return only extension

<?php

print_r(pathinfo("myfile.png",PATHINFO_EXTENSION));

Output: png

?>

Monday 23 December 2013

Show Uploaded Image Preview using JQuery


<style>
    img{
        border: 1px solid #000; 
        padding: 2px;
        border-radius: 5px;
        background: #FFF;
    }
</style>


<input type="file" name="myimage" id="myimage">
<img id="preview" alt="View Image" width="250px" height="250px"/>


<script type="text/javascript">
    $("#myimage").change(function() {
        if (this.files && this.files[0]) {            
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#preview').attr('src', e.target.result);
            }
            reader.readAsDataURL(this.files[0]);
        }
    });
</script>

Demo

Sunday 8 December 2013

Pan card validation using JQuery Validate

PAN card number is a unique national number issued in India for tax related purposes.

Add jquery.js & jquery.validate Plugin

<script type="text/javascript" src="/js/jquery.js"></script>

<script type="text/javascript" src="/js/jquery.validate.js"></script>

Create HTML Form

<form action="action_name" method="POST" id='myform'>
<input type='text' name='pan'>
<input type='submit' value='Submit' name='submit'>
</form>

JQuery Validate Code

<script type='text/javascript'>
   $.validator.addMethod("pan", function(value, element)
    {
        return this.optional(element) || /^[A-Z]{5}\d{4}[A-Z]{1}$/.test(value);
    }, "Invalid Pan Number");


$("#myform").validate({
        rules: {
            "pan": {pan: true},
        },
    });
</script>

Wednesday 13 November 2013

How to Get And Set Selected Dropdown Value in JQuery

<script type='text/javascript'>
// Get selected dropdown value

var country = $("#country option:selected").val();

// Set Selected dropdown value to another dropdown

$("#temp #country_id option[value='" + country + "']").attr("selected", "selected");
</script>

Working with Yii Active Record

findAll Syntax:

<?php
$data = Test::model()->findAll('id=:id', array(':id' => (int) $_POST['id']));
foreach ($data as $row) {
echo "" . $row->attributes['id'] . "";
echo "" . $row->attributes['name'] . "";
}
?>

findAll with DropDownList Syntax:

<?php
echo $form->labelEx($model, 'test_id');
$list = CHtml::listData(Test::model()->findAll('is_active=1', array('order' => 'name')), 'test_id', 'name');
echo $form->dropDownList($model, 'test_id', $list, array('empty' => 'Select Test Type'));
echo $form->error($model, 'test_id');
?>

findAllByAttribute Syntax

<?php
$data = Test::model()->findAllByAttributes(array('name' => explode(",", $_POST['type'])));
foreach ($data as $row) {
//Your Statement
}
?>

updateByPk Syntax

<?php
$model = $this->loadModel($id);
Test::model()->updateByPk($model->id, array("is_active" => 0));
?>

deleteAll by id Syntax

<?php
Test::model()->deleteAll("id=".$_POST['id']);
?>

CDbCriteria Find() Condition (Syntax 1)

<?php
$criteria = new CDbCriteria;
$criteria->condition = 'user_id =1 AND status=1';
$folder = Test::model()->find($criteria);
?>

CDbCriteria Find() Condition (Syntax 2)

<?php
$email='test@example.com';
$criteria = new CDbCriteria;
$criteria->select = 'name';
$criteria->condition = 'id=:id OR email=:email';
$criteria->params = array(':id' => $_GET["id"], ':email' => $email);
$result = Test::model()->find($criteria);
?>

Working with Yii Create Command

Select * Query using Create Command

<?php

// Example 1:

$sql = "SELECT * FROM table WHERE col1='data' AND col2=$id";
$result = Yii::app()->db->createCommand($sql)->query();
$rowCount = $result->rowCount;

// Example 2:

$sql = "SELECT * FROM table WHERE colname = '" . $_POST['data'] . "'";
$dbCommand = Yii::app()->db->createCommand($sql);
$data = $dbCommand->queryAll();
foreach ($data as $row) {
//------
//your statement
//------
}

?>

Insert into using Create Command

<?php
Yii::app()->db->createCommand()->insert('tablename', array(
  'col1' => col1data, 
  'col2' => col2data, 
  'col3' => "col3data" //varchar datatype
));
?>

Update Query using Create Command

<?php
Yii::app()->db->createCommand
("UPDATE user SET name = $name WHERE email=:em AND id=:cid")
->bindValues(array(':em' => "test@example.com", ':cid' => $id))
->execute();
?>

Delete Query using Create Command

<?php
Yii::app()->db->createCommand()->delete('colname', 'col_id=:id', array(':id' => $id));
?>

End Date should be greater than Start Date using CJuiDatePicker

<?php 
echo $form->labelEx($model, 'start_date');
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'htmlOptions' => array(
'size' => '10', // textField size
'maxlength' => '10', // textField maxlength
'class' => "input-small"
),
'options' => array(
'showAnim' => 'fold',
'dateFormat' => 'yy-mm-dd',
'changeMonth' => true,
'changeYear' => true,
'yearRange' => '2000:2099',
'onSelect' => 'js:function( selectedDate ) {
    // #end_date is the ID of end_date input text field
    $("#end_date").datepicker( "option", "minDate", selectedDate );
     }',
    ),
));

echo $form->labelEx($model, 'end_date');            
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'htmlOptions' => array(
'size' => '10', // textField size
'maxlength' => '10', // textField maxlength                        
'class' => "input-small"
),
'options' => array(
'showAnim' => 'fold',
'dateFormat' => 'yy-mm-dd',
'changeMonth' => true,
'changeYear' => true,
),
));
            
?>

Tuesday 12 November 2013

Remove default label from textFieldRow Yii

Add following labelOptions array in textFieldRow:


'labelOptions' => array('label' => false)

Example:


<?php
echo $form->textFieldRow($model, 'test', array(
'options' => array(
'width' => '200',
),
'labelOptions' => array('label' => false)
));
?>

Sunday 10 November 2013

How to get model attributes error in Yii Framework

getErrors() Method: It Returns the errors for all attribute or a single attribute.

Reference: http://www.yiiframework.com/doc/api/1.1/CModel#getErrors-detail

Example:
<?php
$valid = $model->validate();
print_r($model->getErrors());
exit;  //To show validation errors

if ($valid) {
    $model->save();
}
?>

How to run .sh file in Ubuntu command prompt

Give execute permission to your script

Example:

chmod +x /path/to/yourscript.sh


And to run your script

Example:

bash /path/to/yourscript.sh

How to calculate EMI using JQuery

Formula: EMI = (P * r/12) * [ (1+r/12)^n] / [ (1+r/12)^n-1]

Where,
P = Outstanding Principle
r = Interest Rate
n = Tenure (in months)


Following is the JS Code to calculate EMI

<script type="text/javascript">
function calculateEMI(obj) {                                               
 // Formula: 
 // EMI = (P * R/12) * [ (1+R/12)^N] / [ (1+R/12)^N-1]                               
                
 // isNaN(isNotaNumber): Check whether the value is Number or Not                
    if (!isNaN(obj.value) && obj.value.length !== 0) {
                    
    var emi = 0;
    var P = 0;
    var n = 1;
    var r = 0;                                       
                    
   // parseFloat: This function parses a string 
  // and returns a floating point number
    if($("#outstanding_principle").val() !== "")
       P = parseFloat($("#outstanding_principle").val());
                   
                        
    if ($("#interest_rate").val() !== "") 
      r = parseFloat(parseFloat($("#interest_rate").val()) / 100);

    if ($("#tenure").val() !== "")
        n = parseFloat($("#tenure").val());
                    
    // Math.pow(): This function returns the value of x to power of y 
    // Example: (5^2)
                    
    // toFixed: Convert a number into string by keeping desired decimals                   
                    
    if (P !== 0 && n !== 0 && r !== 0)
    emi = parseFloat((P * r / 12) * [Math.pow((1 + r / 12), n)] / [Math.pow((1 + r / 12), n) - 1]);
              
    $("#emi").val(emi.toFixed(2));
                
  }
}
</script>

And Following is the HTML code
<table>
   <tr>
     <th>Outstanding Principle</th>
     <th>Interest Rate (%)</th>
     <th>Tenure (in Months)</th>
     <th>EMI</th>
   </tr>
   <tr>
     <td>
       <input type="text" id="outstanding_principle" onchange="calculateEMI(this);">
     </td>
     <td>
       <input type="text" id="interest_rate" onchange="calculateEMI(this);">
     </td>
     <td>
       <input type="text" id="tenure" onchange="calculateEMI(this);">
     </td>
     <td>
       <input type="text" readonly="true" id="emi">
     </td>
 </tr>                
</table>

Demo

Wednesday 18 September 2013

Simple Drag and Drop Application using JQuery and HTML

Step1: Create a new Web Application

Step2: Add two unordered list, give them some unique ID and same class name


<table>
            <tr>
                <td valign="top">
                    <ul id="sort1" class="dragdrop">
                        <li>Item1 </li>
                        <li>Item2</li>
                    </ul>
                </td>
                <td valign="top">
                    <ul id="sort2" class="dragdrop">
                        
                    </ul>
                </td>
            </tr>
</table>

Id is used to apply styling to the list elements and class is used to enable drag-drop functionality on lists.

Step3: Now add an element to any of the list item. Apply some styling to list and list item using following code inside head tag


<style type="text/css">
        #sort1, #sort2     
        {
            list-style-type: none;
            padding: 10px;
            margin: 5px;
            width: 200px;
            background: #FFDAB9;
            vertical-align:top;
        }
        #sort1 li, #sort2 li            
       {
            border: 2px;
            padding: 5px;
            margin: 5px;
            background: #9ACD32;
            cursor: pointer;
            border-color: Black;
            width: 180px;
            text-align: center;
            vertical-align: middle;
        }
</style>

To enable the drag-drop functionality, add reference of the following java script files. These files are accessed from Google CDN.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js" type="text/javascript"></script>

The following java script code will enable drag-drop on list items.

<script type="text/javascript">
        $(function () {
            $("ul.dragdrop").sortable({  
                connectWith: "ul"
            });
        });
</script>

Here “drag drop” is the class which we have declared for the unordered list. The drag drop is used to identify the list element, on which we are applying “sortable” functionality so that the items inside list can be freely move from one list to another list or within the same list.
Now you can run the application in browser and try to drag Item2 from list1 and try to put it into list2. You can freely move one item into another list or in same list.

Thanks :)

Useful Git Commands

Clone Command:

git clone "Your_remote_source_name"

Check Status:

git status

Create branch:

git branch "Name_of_your_new_branch"

Change branch:

git checkout "Your_branch_name"

View all branch:

git branch

Add project:

git add .

Commit Project:

git commit -m "Your_comments"

Push Project:

git push origin "Your branch Name"

Pull Project:

git pull origin "Your branch Name"

Clone specific branch in git:

git clone -b "Your_branch_name" "Your_remote_source_name"

Rename local branch in git:

git branch -m "old_branch_name" "new_branch_name"

If you want to rename the current branch, you can simply do:

git branch -m "new_branch_name"

Delete specific branch in git:

git branch -D "Your_branch_name"

To Remove deleted files from Git Repository use following command:

git add .
git commit -a -m "Message_in_quote"

Initialize directory and push to remote repository:

git init
git add .
git commit -m "first commit"
git remote add origin your-remote-repo-url
git push -u origin master OR git clone origin master
Reference: https://www.kernel.org/pub/software/scm/git/docs/

Learn Git branching:

https://learngitbranching.js.org/

GitSheet

https://gitsheet.wtf/

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.

Tuesday 4 June 2013

Simple palindrome program in PHP

» What is Palindrome?

It is a word or phrase that is the same spelled forwards and backwards. Example: madam, level, Malayalam etc.

» Find string palindrome or not in PHP using strrev() function

<?php
$word = "level";  // declare a varibale
echo "String: " . $word . "<br>";
$reverse = strrev($word); // reverse the word
if ($word == $reverse) // compare if  the original word is same as the reverse of the same word
    echo 'Output: This string is a palindrome';
else
    echo 'Output: This is not a palindrome';
?>

» Find string palindrome or not in PHP without using strrev() function

<?php
$mystring = "level"; // set the string
echo "String: " . $mystring;
$myArray = array(); // php array
$myArray = str_split($mystring); //split the array
$len = sizeof($myArray); // get the size of array
$newString = "";

for ($i = $len; $i >= 0; $i--) {
    $newString.=$myArray[$i];
}
echo "<br>";
if ($mystring == $newString) {
    echo "Output: " . $mystring . " is a palindrome";
} else {
    echo "Output: " . $mystring . " is not a palindrome";
}
?>

Thursday 23 May 2013

JQuery Multiple Checkbox Select/Deselect in the specific column of table

HTML - JQuery code to select and deselect checkboxes in the specific column of table. We can achieve this with very few line of JQuery code. Following are various JQuery methods which we are going use in our code.




» closest()

It begins with the current element and travels up the DOM tree until it finds a match for the supplied selector. The returned jQuery object contains zero or one element

» find()

You can use the find() to search through all the descendants(child, grandchild, great-grandchild…any levels deep) of the matched element

» index()

The index() method returns the index position of specified elements relative to other specified elements

» children()

Get the children of each element in the set of matched elements, optionally filtered by a selector. The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while


» HTML Code

<table id="tbl-checkbox">
    <tr><th colspan="4">Select All</th></tr>
    <tr>        
        <td><input type="checkbox" class="selectall" /></td>
        <td><input type="checkbox" class="selectall" /></td>
        <td><input type="checkbox" class="selectall" /></td>
        <td><input type="checkbox" class="selectall" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
</table>

» JQuery Code

<script src="js/jquery-1.8.3.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $(".selectall").click(function(){
                     var tbl = $(this).closest("#tbl-checkbox");
            var col_index = $(this).closest("tr").children().index($(this).closest("td")) + 1;
            tbl.find("td:nth-child("+col_index+") input:checkbox").attr("checked",$(this).is(":checked"));
        });        
    });
</script>