Displaying 31-40 of 113 results.
Resolved: Yii 1.1 Cgridview filter listdata without findAll from db, with php array
posted by admin on November 7, 2016
I have CGridView with select filter, and I want to insert select box info manually with php array.
Now I have result with findAll():

<?php $this->widget('zii.widgets.grid.CGridView', array(
'filter' => CHtml::listData(Status::model()->findAll(), 'id', 'name'),
Read more
Wiki: Yii 1.1 app db createCommand execution of SQL statement wayswiki
posted by admin on November 7, 2016
Once a database connection is established, SQL statements can be executed using CDbCommand. One creates a CDbCommand instance by calling CDbConnection::createCommand() with the specified SQL statement:

$connection=Yii::app()->db; // assuming you have configured a "db" connection
// If not, you may explicitly create a connection:
// $connection=new CDbConnection($dsn,$username,$password);
// if needed, the SQL statement may be updated as follows:
// $command->text=$newSQL;

A SQL statement is executed via CDbCommand in one of the following two ways:
  • execute(): performs a non-query SQL statement, such as INSERT, UPDATE and DELETE. If successful, it returns the number of rows that are affected by the execution.
  • query(): performs an SQL statement that returns rows of data, such as SELECT. If successful, it returns a CDbDataReader instance from which one can traverse the resulting rows of data. For convenience, a set of queryXXX() methods are also implemented which directly return the query results.

An exception will be raised if an error occurs during the execution of SQL statements.

$rowCount=$command->execute(); // execute the non-query SQL
$dataReader=$command->query(); // execute a query SQL
$rows=$command->queryAll(); // query and return all rows of result
$row=$command->queryRow(); // query and return the first row of result
$column=$command->queryColumn(); // query and return the first column of result
$value=$command->queryScalar(); // query and return the first field in the first row
//in Russian
$rowCount=$command->execute(); // выполнение запроса типа `INSERT`, `UPDATE` или `DELETE`
$dataReader=$command->query(); // выполнение запроса типа `SELECT`
$rows=$command->queryAll(); // возвращает все строки результата запроса
$row=$command->queryRow(); // возвращает первую строку результата запроса
$column=$command->queryColumn(); // возвращает первый столбец результата запроса
$value=$command->queryScalar(); // возвращает значение первого поля первой строки результата запроса
Read more
Wiki: Yii 1.1 new CDbCriteriawiki
posted by admin on November 7, 2016

// создаем экземпляр класса CDbCriteria
$criteria = new CDbCriteria;
// выбираемые все столбцы из всех таблиц, участвующих в запросе
$criteria->select = '*';
//$criteria->select = array('post.id', 'post.category_id', 'post.user_id', 'post.title', 'user.name');
//$criteria->select = 'post.id, post.category_id, post.user_id, post.title, user.name';
// псевдоним(алиас) для текущей таблицы
$criteria->alias = 'post';
// выбираем только неповторяющиеся строки данных
$criteria->distinct = true;
// задаем условие запроса
$criteria->condition = 'post.is_hide = :is_hide AND post.user_id = :author_id';
// группируем
$criteria->group = 'post.category_id';
// условие для GROUP BY
$criteria->having = 'post.viwed > 100';
// задаем соединение с другой(ими) таблицами
$criteria->join = 'LEFT JOIN users as user ON user.id = post.user_id';
// максимальное количество возвращаемых записей
$criteria->limit = 20;
// смещение, с которого будут возвращаться записи
$criteria->offset = 5;
// сортировки результатов запроса
$criteria->order = 'post.date_create';
// параметры для замены в SQL выражении, для condition
$criteria->params = array(':is_hide'=>0, ':author_id'=>Yii::app()->user->id);
// внешние таблицы должны быть связаны с первичной таблицей в одном SQL-запросе
$criteria->together = true;
// получение связанных объектов в режиме "жадной" загрузки
$criteria->with = array('profile', 'comments', 'category');
// добавляем условие between (диапазон)
$criteria->addBetweenCondition('post.date_update', '09-12-2011', '09-12-2015');
// добавляем условие для сравнения переданного списка со значениями столбцов
$criteria->addColumnCondition(array('status'=>1), 'AND')
// добавляем условие IN к уже имеющемуся (condition)
$criteria->addInCondition('post.category_id', array('6', '24', '247'), 'OR');
// добавляем условие к уже имеющемуся (condition)
$criteria->addCondition("count_comments <= :count_comments");
// сливает критерий с другим
$criteriaSearch = new CDbCriteria();
$criteriaSearch->addSearchCondition('description', $_POST['search_text']. true, 'AND', 'LIKE');
$criteria->mergeWith($criteriaSearch, 'AND');
$posts = Post::model()->findAll($criteria);
Read more
Wiki: Yii 1.1: CGridView. Add custom class to table rows preserving original odd and evenwiki
posted by admin on November 3, 2016
Lets say we have such a CGridView widget showing a list of users for administrator. Users have status „active“ or „disabled“. Grid widget puts class „odd“ or „even“ to rows and we want to preserve this. So we want to add a class „disabled“ to rows with disabled users.

$this->widget('zii.widgets.grid.CGridView', array(
'rowCssClassExpression' => '
( $row%2 ? $this->rowCssClass[1] : $this->rowCssClass[0] ) .
( $data->status ? null : " disabled" )
'name' => 'status',
'value' => '$data->status0->title',
'header' => Yii::t( 'app', 'Tools' ),

$model here is a User model pushed to view from controller. $data->status0->title here is User's property from relation to other model (why it is $data and not $model see bellow).
All „magic“ we do in „rowCssClassExpression“ property. Its value is a PHP expression. Expression is evaluated for every data row. Result of evaluation is used as the CSS class name. Note, that PHP expression is string.
We put „rowCssClassExpression“ property to „top“ CGridView properties – thus class will be aplied to row. If we put another „cssClassExpression“ property to some column – we can set a class for single cell. E.g.:

'name' => 'status',
'value' => '$data->status0->title',
'cssClassExpression' => '"foo" . (2+3) ."bar"',

as result we will have

<td class="foo5bar">

(note the difference between „rowCssClassExpression“ and „cssClassExpression“) From widget you can access such a variables:
  • $row : the row number (zero-based)
  • $data : the data model for the row
  • $this : the column object. As you can see we use all of them.


( $row%2 ? $this->rowCssClass[1] : $this->rowCssClass[0] ) .

evaluates to 0,1,0,1... as rows are processed and original „odd“ or „even“ values are returned. CGridView::rowCssClass property is array containing default class values (in means of html element attribute). This property is ignored in widget because of rowCssClassExpression property is used. But values are accessible :) This expressions then is concatenated (note dot at the end) with:

( $data->status ? null : " disabled" )

$data here is User model and „status“ is its property (0 or 1 in this case). You can't access $model variable from those string expressions.Read more
Resolved: Yii 1.1 Change assets folder path directory from assets to another
posted by admin on October 31, 2016
By default we have assets folder, and in server I cant create folder in assets, or copy assets folders with files, I got an internal server error, and website generate js and css errors. How I can change assets folders to another directory.Read more
Resolved: Yii 1.1 listdata multiple fields
posted by admin on October 25, 2016
I have form with select box, and want to generate options with multiple columns.

$criteria = new CDbCriteria();
...//if you have criteria condition
$type_list=CHtml::listData(Paper::model()->findAll($criteria),'id','title'); ?>
<?php echo $form->dropDownList($model, 'paper_id', array(''=>Yii::t('t', 'Выберите бумагу'))+$type_list, array('options' => array($model->paper_id=>array('selected'=>true)))); ?>

In output i see:
  • Title 1
  • Title 2
  • etc...
  • Title N

But I want multiple columns, and want to see output like this:
  • Title 1, field 1, another field 1, etc...
  • Title 2, field 2, another field 2, etc...
  • ...
  • Title N, field N, another field N, etc...
Read more
Resolved: Yii 1.1 Relation to same model relations HAS_MANY BELONGS_TO error
posted by admin on October 12, 2016
I have this error
Trying to get property of non-object
php code

($model->creator_id) ? $model->creator->firstname . ' ' . $model->creator->lastname : 'Нет',

model relations:

public function relations()
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'creator' => array(self::BELONGS_TO, 'User', 'creator_id'),
'creator' => array(self::HAS_MANY, 'User', 'creator_id'),
Read more
Resolved: Yii 1.1 How to get attribute from model attributeLabels function in CDetailView custom field
posted by admin on October 12, 2016
I have this CDetailView

<?php $this->widget('zii.widgets.CDetailView', array(
'label' => Yii::t('translation', 'Created'),
'type' => 'raw',
'value' => app::datetimeUserFriendly($model->created),
. . .
)); ?>

I want to read label from model attributeLabels.Read more
Wiki: Yii 1.1 Cgridview TextField Search and Filter of a relations field without errorswiki
posted by admin on October 11, 2016
1) Add some public attribute to the model.

class Customer extends CActiveRecord
public $customername; // for firstname + lastname;

2) Declare it safe on search.

public function rules()
return array(
array('id, firstname, lastname, ...., customername', 'safe', 'on'=>'search'),

3) Set the label for it.

public function attributeLabels()
return array(
'id' => 'ID',
'firstname' => 'First Name',
'lastname' => 'Last Name',
'customername' => 'Customer Name',

4) Add a search condition for it in "search()" method.

public function search()
$criteria=new CDbCriteria;

if ( $this->customername != "" )
$crit2 = new CDbCriteria;
$crit2->compare('firstname', $this->customername , true, 'OR');
$crit2->compare('lastname', $this->customername , true, 'OR');

5) Add the sorting rule for it, also in the "search()" method.

return new CActiveDataProvider(get_class($this), array(
'criteria' => $criteria,
'sort' => array(
'defaultOrder' => 'lastname, firstname',
'attributes' => array(
'customername' => array(
'asc' => 'lastname, firstname',
'desc' => 'lastname DESC, firstname DESC',
'pagination' => array(
'pageSize' => 20,

6) And use the attribute in the grid.

$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'customer-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'name' => 'customername',
'value' => '$data->firstname . " " . $data->lastname',
Read more
Resolved: Yii 1.1 Cmenu item url array working by wrong logic
posted by admin on October 11, 2016
Cmenu item url working not correct.
It take my current url and the compose new url, and it is wrong.
For example it looks like like this


But I have only module Stores and want to view result:


My Cmenu array is here:

array('label'=>'Таблицы <span class="caret"></span>', 'url'=>array('#'),
'linkOptions'=> array(
'class' => 'dropdown-toggle',
'data-toggle' => 'dropdown',
'items' => array(
array('label' => 'Пользователи', 'url' => array('stores/user')),
array('label' => '', 'url' => array('#'), 'itemOptions'=>array('role'=>'separator', 'class'=>'divider')),
Read more