Posts Tagged with yii 1

Displaying 1-10 of 70 results.
Resolved: Yii2 ActiveForm password autocomplete off chrome not working
posted by admin on June 9, 2017
I have ActiveForm in Yii2 and password section and username filled automatically and autocomplete="off" not working on Chrome

<?php $form = ActiveForm::begin([
'options' => [
//'autocomplete' => 'off'
],
]); ?>
. . .
<div class="row">
<div class="col-md-12">
<?= $form->field($model, 'password_change')->passwordInput(['maxlength' => true, 'autocomplete' => 'off'])->label('password') ?>
</div>
</div>
. . .
<?php ActiveForm::end(); ?>
Read more
Wiki: CActiveRelation HAS_MANY BELONGS_TO based on secondary keywiki
posted by admin on November 16, 2016
In the Model class, I overrode the getTableSchema and manually defined the foreign keys like so:

public function getTableSchema()
{
$table = parent::getTableSchema();

$table->columns['sid']->isForeignKey = true;
$table->foreignKeys['sid'] = array('Click', 'm_sid');

return $table;
}

And in the corresponding table:

public function getTableSchema()
{
$table = parent::getTableSchema();

$table->columns['m_sid']->isForeignKey = true;
$table->foreignKeys['m_sid'] = array('Message', 'sid');

return $table;
}

Now the standard relation definitions work directly!

'clicks'=>array( self::HAS_MANY, 'Click', 'm_sid' ),

as well as

'message'=>array( self::BELONGS_TO, 'Message', 'sid'),
Read more
Resolved: Hosting iPage.com MySQL connection error: SQLSTATE[HY000] [2002] Connection refused
posted by admin on November 11, 2016
I am trying to run my Yii 1 website and connect to DB, which is not in my hosting iPage.com and have this error:

CDbConnection failed to open the DB connection: SQLSTATE[HY000] [2002] Connection refused

For example, my MySQL config in iPage.com working fine
protected/config/database.php

<?php
return array(
'connectionString' => 'mysql:host=*******.ipagemysql.com;dbname=somename',
'emulatePrepare' => true,
'username' => 'someuser',
'password' => 'somepassword',
'charset' => 'utf8',
);

Another server connection and error
protected/config/database.php

<?php
return array(
'connectionString' => 'mysql:host=anotherhostname;dbname=somename',
'emulatePrepare' => true,
'username' => 'someuser',
'password' => 'somepassword',
'charset' => 'utf8',
);

Error:

CDbConnection failed to open the DB connection: SQLSTATE[HY000] [2002] Connection refused
Read more
Wiki: Yii 1.1 right way to pass parametr to model search from relation controller and view (usage in CGridView)wiki
posted by admin on November 9, 2016
Models:

* @property integer $id
* @property integer $type_id
* @property string $name
class Store extends CActiveRecord
{
//...
public function rules()
{
return array(
//your rules
array('id, type_id, name', 'safe', 'on'=>'search, searchbytype'),
);
}

public function relations()
{
return array(
'type' => array(self::BELONGS_TO, 'Type', 'type_id'),
);
}

public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('t.id',$this->id);
$criteria->compare('t.name',$this->name,true);
$criteria->compare('t.type_id',$this->type_id);

return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'sort' => array(
'defaultOrder' => 't.id DESC',
'attributes' => array(
'*',
),
),
'pagination' => array (
'PageSize' => 50 //edit your number items per page here
),
));
}

//Our custom search with recieve passed parametrs
public function searchbytype($id)
{
$criteria=new CDbCriteria;
//add condition here
$criteria->condition = "t.type_id = ".$id;

$criteria->compare('t.id',$this->id);
$criteria->compare('t.name',$this->name,true);
$criteria->compare('t.type_id',$this->type_id);

//do not add condition here, filter search not working correct
//$criteria->condition = "t.type_id = ".$id;

return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'sort' => array(
'defaultOrder' => 't.id DESC',
'attributes' => array(
'*',
),
),
'pagination' => array (
'PageSize' => 50 //edit your number items per page here
),
));
}

//...
}

class Type extends CActiveRecord
{
//...
public function relations()
{
return array(
'store' => array(self::HAS_MANY, 'Store', 'type_id'),
);
}
//...
}


Controller:

class TypeController extends Controller
{
//...
public function actionView($id)
{
$model = $this->loadModel($id);
$stores=new Store('searchbytype');
$stores->unsetAttributes(); // clear any default values
if(isset($_GET['Store']))
$stores->attributes=$_GET['Store'];
$this->render('view',array(
'model'=>$model,
'stores'=>$stores
));
}
//...
}

View:

<h1><?php echo $model->id; ?></h1>
<?php
$id = Yii::app()->request->getQuery('id');

$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'application-grid',
'dataProvider'=>$stores->searchbytype($id),
'filter'=>$stores,
'pagerCssClass' => 'pagination pull-right',

'columns'=>array(
'id',
'name',
array(
'class'=>'CButtonColumn',
),
),
));
Read more
Resolved: Yii 1.1 CHtml activeDropDownList htmlOptions
posted by admin on November 8, 2016
I have , and want to add htmlOPtions array, for example style, or class etc...

CHtml::activeDropDownList($model, 'status_id', array_combine(array_values(array("", "3", "1")), array("Все", "Заявки", "В ожидании")));
Read more
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(
'id'=>'application-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
...
array(
'name'=>'status_id',
'value'=>'$data->status->name',
'type'=>'html',
'filter' => CHtml::listData(Status::model()->findAll(), 'id', 'name'),
),
...
),
)
);
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");
// сливает критерий с другим
if($_POST['search_text']){
$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.
Implementation

<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'rowCssClassExpression' => '
( $row%2 ? $this->rowCssClass[1] : $this->rowCssClass[0] ) .
( $data->status ? null : " disabled" )
',
'columns'=>array(
'username',
array(
'name' => 'status',
'value' => '$data->status0->title',
),
array(
'class'=>'CButtonColumn',
'header' => Yii::t( 'app', 'Tools' ),
),
),
));
?>

Comments
$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).
rowCssClassExpression
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.
cssClassExpression
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.:

<?php
array(
'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.

Expressions
This

( $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.
Now:

$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