Displaying 21-30 of 109 results.
Wiki: Installing Yii2 in XAMPP to htdocs directorywiki
posted by admin on February 1, 2017
The First, dont forget to install "fxp/composer-asset-plugin:^1.2.0"

php composer.phar global require "fxp/composer-asset-plugin:^1.2.0"

Waiting for result

Changed current directory to C:/Users/Arthur/AppData/Roaming/Composer
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Installing fxp/composer-asset-plugin (v1.2.2) Downloading: 100%
Writing lock file
Generating autoload files

The Second, start instalation

c:\xampp\php>php composer.phar create-project --prefer-dist yiisoft/yii2-app-bas
ic ../htdocs/yiibasic

Waiting for result

Installing yiisoft/yii2-app-basic (2.0.10)
- Installing yiisoft/yii2-app-basic (2.0.10) Downloading: 100%
Created project in ../htdocs/yiibasic
Loading composer repositories with package information
Updating dependencies (including require-dev)
Reading bower.json of bower-asset/jquery (1.11.3)
Could not fetch https://api.github.com/repos/jquery/jquery-dist/commits/14722909
17f17af05e98007136096784f9051fab, please create a GitHub OAuth token to go over
the API rate limit
Head to https://github.com/settings/tokens/new?scopes=repo&description=Composer+
on+dev-pk+2017-02-01+0920
to retrieve a token. It will be stored in "C:/Users/╚фЁшё/AppData/Roaming/Compos
er/auth.json" for future use by Composer.
Token (hidden):
Token stored successfully.
Package operations: 58 installs, 0 updates, 0 removals
- Installing yiisoft/yii2-composer (2.0.5) Downloading: 100%
- Installing swiftmailer/swiftmailer (v5.4.5) Downloading: 100%
- Installing bower-asset/jquery (2.2.4) Downloading: 100%
- Installing bower-asset/yii2-pjax (v2.0.6) Downloading: 100%
- Installing bower-asset/punycode (v1.3.2) Downloading: 100%
- Installing bower-asset/jquery.inputmask (3.2.7) Downloading: 100%
- Installing cebe/markdown (1.1.1) Downloading: 100%
- Installing ezyang/htmlpurifier (v4.8.0) Downloading: 100%
- Installing yiisoft/yii2 (2.0.10) Downloading: 100%
- Installing yiisoft/yii2-swiftmailer (2.0.6) Downloading: 100%
- Installing bower-asset/bootstrap (v3.3.7) Downloading: 100%
- Installing yiisoft/yii2-bootstrap (2.0.6) Downloading: 100%
- Installing yiisoft/yii2-debug (2.0.7) Downloading: 100%
- Installing bower-asset/typeahead.js (v0.11.1) Downloading: 100%
- Installing phpspec/php-diff (v1.1.0) Downloading: 100%
- Installing yiisoft/yii2-gii (2.0.5) Downloading: 100%
- Installing fzaninotto/faker (v1.6.0) Downloading: 100%
- Installing yiisoft/yii2-faker (2.0.3) Downloading: 100%
- Installing sebastian/diff (1.4.1) Downloading: 100%
- Installing sebastian/recursion-context (2.0.0) Downloading: 100%
- Installing sebastian/exporter (2.0.0) Downloading: 100%
- Installing sebastian/comparator (1.2.4) Downloading: 100%
- Installing behat/gherkin (v4.4.5) Downloading: 100%
- Installing symfony/polyfill-mbstring (v1.3.0) Downloading: 100%
- Installing symfony/dom-crawler (v3.2.2) Downloading: 100%
- Installing symfony/css-selector (v3.2.2) Downloading: 100%
- Installing symfony/browser-kit (v3.2.2) Downloading: 100%
- Installing symfony/yaml (v3.2.2) Downloading: 100%
- Installing symfony/event-dispatcher (v3.2.2) Downloading: 100%
- Installing psr/log (1.0.2) Downloading: 100%
- Installing symfony/debug (v3.2.2) Downloading: 100%
- Installing symfony/console (v3.2.2) Downloading: 100%
- Installing symfony/finder (v3.2.2) Downloading: 100%
- Installing psr/http-message (1.0.1) Downloading: 100%
- Installing guzzlehttp/psr7 (1.3.1) Downloading: 100%
- Installing sebastian/version (2.0.1) Downloading: 100%
- Installing sebastian/environment (2.0.0) Downloading: 100%
- Installing sebastian/code-unit-reverse-lookup (1.0.0) Downloading: Connectin
Downloading: 100%
- Installing phpunit/php-token-stream (1.4.9) Downloading: 100%
- Installing phpunit/php-text-template (1.2.1) Downloading: 100%
- Installing phpunit/php-file-iterator (1.4.2) Downloading: 100%
- Installing phpunit/php-code-coverage (4.0.5) Downloading: 100%
- Installing sebastian/resource-operations (1.0.0) Downloading: 100%
- Installing sebastian/object-enumerator (2.0.0) Downloading: 100%
- Installing sebastian/global-state (1.1.1) Downloading: 100%
- Installing doctrine/instantiator (1.0.5) Downloading: 100%
- Installing phpunit/phpunit-mock-objects (3.4.3) Downloading: 100%
- Installing phpunit/php-timer (1.0.8) Downloading: 100%
- Installing webmozart/assert (1.2.0) Downloading: 100%
- Installing phpdocumentor/reflection-common (1.0) Downloading: 100%
- Installing phpdocumentor/type-resolver (0.2.1) Downloading: 100%
- Installing phpdocumentor/reflection-docblock (3.1.1) Downloading: Connecting
Downloading: 100%
- Installing phpspec/prophecy (v1.6.2) Downloading: 100%
- Installing myclabs/deep-copy (1.6.0) Downloading: 100%
- Installing phpunit/phpunit (5.7.9) Downloading: 100%
- Installing codeception/base (2.2.8) Downloading: 100%
- Installing codeception/verify (0.3.2) Downloading: 100%
- Installing codeception/specify (0.4.6) Downloading: 100%
symfony/browser-kit suggests installing symfony/process ()
symfony/event-dispatcher suggests installing symfony/dependency-injection ()
symfony/event-dispatcher suggests installing symfony/http-kernel ()
symfony/console suggests installing symfony/filesystem ()
symfony/console suggests installing symfony/process ()
phpunit/php-code-coverage suggests installing ext-xdebug (>=2.4.0)
sebastian/global-state suggests installing ext-uopz (*)
phpunit/phpunit-mock-objects suggests installing ext-soap (*)
phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)
phpunit/phpunit suggests installing ext-xdebug (*)
codeception/base suggests installing flow/jsonpath (For using JSONPath in REST m
odule)
codeception/base suggests installing phpseclib/phpseclib (for SFTP option in FTP
Module)
codeception/base suggests installing league/factory-muffin (For DataFactory modu
le)
codeception/base suggests installing league/factory-muffin-faker (For Faker supp
ort in DataFactory module)
codeception/base suggests installing symfony/phpunit-bridge (For phpunit-bridge
support)
Writing lock file
Generating autoload files
> yii\composer\Installer::postCreateProject
chmod('runtime', 0777)...done.
chmod('web/assets', 0777)...done.
chmod('yii', 0755)...done.
Read more
Wiki: Установка Yii под XAMPP в Windows 8wiki
posted by admin on January 21, 2016
Здесь я подробно расскажу, как установить Yii - фрэймфорк под популярную сборку веб-сервера XAMPP в операционной системе Windows 8.

Для работы Yii - фрэймфорка, необходим PHP версии 5.1 и выше, a в ближайшем будущем появится новая версия фрэймворка в которой уже понадобится как минимум версия 5.3.

Для работы с проектами на локальном компьютере на данный момент я использую XAMPP 3.0.12 c версией php 5.4. Скачать XAMPP можно здесь.

Лично я настроил XAMMP так, что все проекты у меня хранятся на диске D в папке PHP, чего и вам советую.

Что касается самого yii-фрэймворка, скачть его можно здесь. Пример развертывания проекта у меня будет происходить на версии yii 1.1.4.

Создаем в папке php новую папку с проектом. Я назвал ее learn.loc. Далее, для нового проекта настраиваем виртуальные хосты и т.д.. В общем, все стандартные действия, чтобы после введения в строку браузера http://learn.loc ваш проект не послал вас на 404 или куда-то в подобном направлении.

Распакуем в корень папки learn.loc скачанный фрэймворк.

Теперь настало время консоли windows. Вывзываем консоль (надеюсь, как это сделать объяснять не надо) и вводим такое заклинание:

C:/xampp/php/php.exe C:/xampp/htdocs/learn.loc/framework/yiic webapp C:/xampp/htdocs/learn.loc/

Где C:/xampp/php/php.exe - путь до исполняемого файла php, C:/xampp/htdocs/learn.loc/framework/yiic - путь до файла во вреймворке, который развертывает проект, а C:/xampp/htdocs/learn.loc/ - путь куда мы хотим развернуть проект.

Далее, в консоли у нас спросят, внтатуре ли мы отвечем за базар. Вводим y (yes) и наслаждаемся бегущими строчками на черном экране. Типа вы архитектор матрицы.

На этом всё. Делее можете проверить, работает ли проект, введя в браузер http://learn.locRead 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: Yii 1.1 Redirect to referrer url
posted by admin on November 10, 2016
I want to redirect from referrer page
Now:

$this->redirect(array('admin'));

I want something like

$this->redirect({referrer});
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 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);
$command=$connection->createCommand($sql);
// 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");
// сливает критерий с другим
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