Friday, 20 June 2014

Yii Grid filter with relations

In Yii there are 3 simple steps to implement filter for relational column in Gridview. Lets Say we have two models and relation between them.

Eg. Consider following example. Here we have 3 models City, State and Country. City has 2 columns state_id and country_id along with their relations.

<?php
    public function relations() {
        return array(
            'country' => array(self::BELONGS_TO, 'Country', 'country_id'),
            'state' => array(self::BELONGS_TO, 'State', 'state_id')
        );
    }
?>

Now after doing customization in City Gridview we need to implement filter for countries and states. Here are the following 3 simple steps to achieve this.

1) In Gridview:

<?php

$this->widget('bootstrap.widgets.TbGridView', array(
    'id' => 'city-grid',
    'template' => '{items}{summary}{pager}',
    'dataProvider' => $model->search(),
    'filter' => $model,
    'columns' => array(
        array(
            'name' => 'country.name',            
            'filter' => CHtml::activeTextField($model, 'country'),      
        ),
        array(
            'name' => 'state.name',
            'filter' => CHtml::activeTextField($model, 'state'),            
        ),
        array(
            'name' => 'name',
            'type' => 'raw',
            'value' => 'CHtml::link($data->name,"/city/update/$data->city_id")',
        ),        
        array(
            'class' => 'bootstrap.widgets.TbButtonColumn',
        ),
    ),
));
?>

Model:

2) In rules array:

<?php
public function rules() {
        return array(
            array('name', 'unique'),
            array('name, country_id', 'required'),
            array('state, country, city_id, country_id, state_id, name', 'safe', 'on' => 'search'),
        );
?>

3) In search() method:

<?php
    public function search() {    
        $criteria = new CDbCriteria;
        $criteria->together = true;
        $criteria->with = array('state', 'country');
        $criteria->compare('city_id', $this->city_id);        
        $criteria->compare('name', $this->name, true);
        $criteria->addSearchCondition('state.name', $this->state);
        $criteria->addSearchCondition('country.name', $this->country);

        $dataProvider = new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));

        return $dataProvider;
    }
?>

That's it! Hope it'll help you.

...See more Yii stuffs

Wednesday, 11 June 2014

Display total amount on Yii Grid

In this example we are displaying total amount of two fields in footer. Here we are calling getTotal() method (Defined in Model. See Step 2) by passing three parameters to it. First parameters is $model->search()->getData() which returns the data items currently available, second and third parameters are the values of amount_1 and amount_2 respectively.

Step 1:

<?php
$this->widget('bootstrap.widgets.TbGridView', array(
    'id' => 'my-grid',
    'dataProvider' => $model->search(),
    'template' => '{items}',
    'columns' => array(
        array(
            'header' =>'Amount 1',
            'name' => 'amount_1',
            'footer'=>'Total (Amount 1 + Amount 2)',
        ),        
        array(
            'header' => 'Amount 2',
            'name' => 'amount_2',
            'footer' => $model->getTotal($model->search()->getData(), 'amount_1','amount_2'),
        ),        
    ),
));
?>

Step 2:

<?php
    public function getTotal($records, $data1, $data2) {
        $total = 0;
        foreach ($records as $record) {
            $total += $record->$data1 + $record->$data2;
        }
        return number_format($total, 2);
    }
?>

Thursday, 24 April 2014

Replace textfield with dropdown yii grid

In Yii CGridview you can replace default text-field with drop-down to filter records. You just need to add following line in your columns array. Ex. I have added "Category" column along with drop-down filter.

     'category'=>array(
        'name' => 'category',
        'value' => '$data->category',
        'filter'=> CHtml::listData(CustomerSpendings::model()->findAll(array('order'=>'category')), 'category', 'category')
    ),

Tuesday, 25 March 2014

Check Yii CGridview empty

If you are working on Yii framework then sometime you need to check whether your CGridView widget (Generated by Yii) has empty data or not. Recently I've faced problem where I've to redirect user to create page if there is no data in CGridView depending on user's role and conditions. After couple of googling I've found few simple lines and modified my model code which worked for me.

In model: Put CActiveDataProvider into a variable:
<?php
    $dataProvider = new CActiveDataProvider($this, array(
        'criteria' => $criteria,
        'pagination' => array('pageSize' => 10),
        'sort' => array(
            'defaultOrder' => 'create_dttm DESC',
        )
    ));
?>
Check if dataprovider is empty or not:
<?php
  if (!isset($_REQUEST['ajax']) && $dataProvider->totalItemCount < 1) {
   Yii::app()->getController()->redirect(array('create'));
  } else {
   return $dataProvider;
  }    
?>
If the above code doesn't works then you can also return an empty data provider like this:
return new CActiveDataProvider($this, array('data' => array()));

Tuesday, 4 March 2014

Simple form cloning in JQuery

Simple JQuery-HTML based form cloning functionality. It not only clones the normal textfield, textarea, file field and dropdown field but also JQuery Datepicker and Maskmoney field.
Maskmoney is just a simple way to create masks to your currency form fields with JQuery. For more reference and live demo check this link : http://plentz.github.io/jquery-maskmoney/

See the demo for more information:


Monday, 3 March 2014

JQuery selectors and how to use them

Get selected text from dropdown

$("#myid option:selected").text();

Get selected value from dropdown

$("#myid option:selected").value();

Get input type text value

$("#myid input[type=text]").val();

Get checked radiobutton value by class

$(".myclass").click(function() {
  var input = $('.myclass:checked').val();
  alert(input);
});

Check whether radiobutton or checkbox checked or not

$("#test").click(function() {
   var check = $('#test').attr('checked');
   if(check === "checked")
        //condition
   else
        //condition
});

Clear all form fields (i.e. text-field, file-field, drop-down, check-box and radio-buttons)

$('input[type="text"]').val('');
$('input[type="file"]').val('');
$('input[type="radio"]').prop('checked', false);
$('input[type="checkbox"]').prop('checked', false);
$("#mydropdown option:selected").prop("selected", false);

If you want to exclude any one field then you can do like this. Ex. you want to exclude one drop-down field

Option1:

$('select[name != "test"]').val('');

Option2:

$("select:not([name='User[name]'], [name='User[email]'])").val("");

Event based on the value of data attribute

$( "input[data-role-type='privilege_role']" )

Get concatenated name in Yii dropDownList

If you have two fields like firstname and lastname in your table then sometime you need to show concatenated name in dropDownList that is name with first name and last name. Following is the post where you will find how to deal with this in Yii Framework.

First of all you need to create method in your model.

Model (User in this case)

<?php
public function getConcatened(){
    return $this->firstname . '  ' . $this->firstname;
}
?>

Then call that function from CHtml list data by passing function name as a third parameter.

In drop down list:

<?php
$list = CHtml::listData(User::model()->findAll(array('order' =>     'firstname')), 'id', 'concatened');
echo $form->dropDownListRow($model, 'id', $list);
?>

Friday, 7 February 2014

How to show protected images in Yii

"protected" folder are not accessible from the client browser. This prevents user to have access to important files. If you want to store images inside "protected" and want them to be accessible, you need to publish them using CAssetManager.

Example:
1
2
$path = Yii::app()->basePath.'/path-inside-protected';
$imgurl= Yii::app()->assetManager->publish($path);
Yii will then use the file as an asset, coping it to the "assets" folder, sibling to "protected". After that, you can just use the url returned on your HTML.
1
<img src="<?php echo $imgurl?>">

Thursday, 16 January 2014

Get column names from model Yii

In previous post we learned how to get table name from model in Yii. In this post we'll learn how to fetch all column names from model name by using our previous method.
Add the following method in your "CommonController.php" or any other which you are using.

<?php
public static function getColumnNames($table) {        
        return $table::model()->getTableSchema()->getColumnNames();
}
?>

Now call that method from your model/view/controller in this way:

<?php
$model=new User;
$table=CommonController::getTableNameFromModel($model);
$colArr=CommonController::getColumnNames($table);

// -- Output --
echo "<pre>";
print_r($colArr);
?>

It'll return you an array containing all the column names of given table.
Thanks. Have a great day.

Get table name from model name Yii

Step1: Create one controller named "CommonController.php" or use any existing one.
Step2: Create a static method in that controller named "getTableNameFromModel()" and add the following code in it.

<?php
public static function getTableNameFromModel($model) {
       return $model::model()->tableSchema->name;
}
?>

Step3: Call function from your model/view/controller by passing model name as a parameter.
<?php
    $model=new User;
    echo CommonController::getTableNameFromModel($model);
?>

It'll return table name of the corresponding model.
Hope it'll help you. Thanks.

Read Next: Get column names from model Yii

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)
));
?>