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

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

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

Monday, 3 March 2014

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

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, 13 November 2013

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

Sunday, 4 August 2013

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.