Advice on Yii. Сhapter 5.
-
An example for use of CArrayDataProvider.
In some cases it is necessary to display the content of the array in CGridView.
CArrayDataProvider will help you to do it.
Сontroller:
- public function actionViewGrid() {
- $items = array(
- array('id' => 1, 'title'=>'Title1', 'description' => 'Description1'),
- array('id' => 2, 'title'=>'Title2', 'description' => 'Description2'),
- array('id' => 3, 'title'=>'Title3', 'description' => 'Description3'),
- array('id' => 4, 'title'=>'Title4', 'description' => 'Description4')
- );
-
- $itemsProvider = new CArrayDataProvider($items, array(
- 'pagination' => array(
- 'pageSize' => 2,
- ),
- ));
-
- $this->render('viewgrid', array('itemsProvider' => $itemsProvider));
- }
View:
- $this->widget('zii.widgets.grid.CGridView', array(
- 'id' => 'itemGrid',
- 'dataProvider' => $itemsProvider,
- 'enablePagination' => true,
- 'columns' => array(
- array(
- 'name' => 'ID',
- 'value' => '$data["id"]',
- 'sortable' => true,
- 'filter' => false,
- ),
- array(
- 'name' => 'Name',
- 'value' => '$data["title"]'
- ),
- array(
- 'name' => 'Description',
- 'value' => '$data["description"]'
- ),
- )
- ));
As a result we will get a usual GridView with an ability for pagination:
Remember that each array should have an id key with a value. Otherwise, it will not work.
-
A couple of useful methods.
In Yii use Yii::app()->session->sessionId instead of session_id() to get the id of a user's session.
Use Yii::app()->request->userHostAddress instead of $_SERVER['REMOTE_ADDR'] to get IP address of a user.
-
CDbExpression.
It is doubtless that in SQL queries many of us use built-in functions NOW(), DATE_FORMAT() etc.
If you just add NOW() inte the query, the result will differ from the one you have expected.
It happens because NOW() is interpreted as a line.
- Yii::app()->db->createCommand()->insert('table', array(
- 'title'=> 'title1',
- 'description'=> 'description1',
- 'date_now' => 'NOW()',
- ));
So you need to use CDbExpression:
- Yii::app()->db->createCommand()->insert('table', array(
- 'title'=> 'title1',
- 'description'=> 'description1',
- 'date_now' => new CDbExpression('NOW()'),
- ));
One more example, but now with DATE_FORMAT:
- $dateNow = new CDbExpression("DATE_FORMAT(date_now, '%Y-%m-%d') AS dateNowFormat");
-
- $allRecords = Yii::app()->db->createCommand()
- ->select('title, description, '.$dateNow.'')
- ->from('table')
- ->queryAll();
or:
- $allRecords2 = Yii::app()->db->createCommand()
- ->select(array('title', 'description', new CDbExpression("DATE_FORMAT(date_now, '%Y-%m-%d') AS dateNowFormat")))
- ->from('table')
- ->queryAll();
or:
- $criteria = new CDbCriteria();
- $criteria->select = new CDbExpression("DATE_FORMAT(date_now, '%Y-%m-%d') AS dateNowFormat");
Discuss the article in the forum