CSqlDataProvider attributeLabels - php

<?php
//form
class SomeForm extends CFormModel
{
public $id;
public $user_id;
public function search()
{
$sql = 'SELECT id, name FROM some_table';
$sql_count = 'SELECT COUNT(id) FROM some_table';
return new CSqlDataProvider($sql, array(
'totalItemCount' => Yii::app()->db->createCommand($sql_count)->queryScalar(),
'sort' => array(
'attributes' => array(
'id', 'name',
),
),
'pagination' => array(
'pageSize' => 50,
),
));
}
public function attributeLabels()
{
return array(
'id' => 'ID',
'name' => 'NAME',
);
}
}
//grid
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(), //$model = new SomeForm()
'columns' => array(
'id',
'name'
),
));
/*
Result:
id | name
---------
1 | John
EXPECTED Result:
ID | NAME
---------
1 | John
*/
How to set custom names for query columns ?

The simplest way:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(), //$model = new SomeForm()
'columns' => array(
'id::ID',
'name::NAME'
),
));
Another way:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(), //$model = new SomeForm()
'columns' => array(
array(
'header' => 'ID',
'name' => 'id'
),
array(
'header' => 'NAME',
'name' => 'name',
),
),
));
Link to api doc

If you don't want to use custom names; if you want to use your labels declared in your model, then you can do this:
Create an empty instance of your model and pass it to your view. The view will thus utilize the $data (CSqlDataProvider) as well as the empty model.
$labelModel = new my_model;
$this->widget('zii.widgets.CListView',array(
'dataProvider'=>$my_model->search(), //returns a CSqlDataProvider
'itemView'=> '_view',
'viewData' => array('labelModel' => $labelModel),
));
Use the empty model - together with getAttributeLabel - to echo labels.
Use $data['field_name'] to echo the data.
This link has more info on how to pass the additional model to the CListView or CGridView.

Related

How can I use DataProvider and CGridView in Yii to display array in array data?

now i have the code like this:
$testArray1 = array(array(
'user_id'=>'1',
'name'=>array(
'david',
'haword'),
),
array(
'user_id'=>'2',
'name'=>'andrew',
),
);
print_r($testArray1);
$arrayDataProvider = new CArrayDataProvider ($testArray1,array(
//'KeyField'=>'_id',
'pagination'=>array(
'pageSize'=>10,
),
'sort'=>array(
),
));
$this->widget('zii.widgets.grid.CGridView', array(
'id' =>'BCImported-grid',
'dataProvider' =>$arrayDataProvider,
'columns' =>array('name'),
));
here is my result:
so the form only display name = andrew,and name = david and haword is not display.
how can I use DataProvider and CGridView in Yii to display array in array data like name = david and haword where 'user_id'=>'1'?
there is no way to display array in CGridView except you custom that value.
create some static function in your model
public static function implodeName($data)
{
if(isset($data['name'])) {
if(is_array($data['name'])) {
return implode(',', $data['name']);
}
else {
return $data['name'];
}
}
return '';
}
then in CGridView will be like this
$this->widget('zii.widgets.grid.CGridView', array(
'id' =>'BCImported-grid',
'dataProvider' =>$arrayDataProvider,
'columns' =>array(
array(
'header' => 'Names',
'name' => 'name',
'value' => 'YourModelName::implodeName($data)'
),
),
));
and the result should be :
david, hawords

Yii: Trying to get property of non-object in view

I am trying to access attributes of the model in the view and it is throwing me the error mentioned in the title. This is my CompanyMask model:
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(
'company' => array(self::BELONGS_TO, 'company', 'company_id'),
);
}
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
// $criteria->select = "t.id, t.company_id, t.mask_id, t.mask_text, c.name as company_name";
// $criteria->join = 'LEFT JOIN company c on c.id=t.company_id';
$criteria->with = array('company');
$criteria->compare('id', $this->id);
$criteria->compare('company_id', $this->company_id);
$criteria->compare('mask_id', $this->mask_id);
$criteria->compare('mask_text', $this->mask_text, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
Now In the view I am trying to access the name of the company like this:
$gridView = $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'deals-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'ajaxUpdate' => 'deals-grid',
'itemsCssClass' => 'table table-striped table-responsive table-bordered no-margin',
'pagerCssClass' => 'pagination pagination-sm no-margin pull-right',
'pager' => array(
'maxButtonCount' => '7',
),
'columns' => array(
array(
'header' => 'Company Name',
'type' => 'raw',
'htmlOptions' => array('style' => 'width:15%',),
'value' => '$data->company->name',
),
),
));
What am I doing wrong here? Any help?
It's about two things:
You are using $data as object, but it's an array: $data['company']->name
You are using single quotes, so the value is the literal value $data->company->name instead of the real value. Remove the single quotes around $data['company']->name

how to make search gridview with custom query in yii

I created a simple gridview using a custom query. This is working fine for me but search box doesn't work. How do I make the search box work?
Here is my code:
UserController.php
public function actionAdmin()
{
$sql = 'SELECT * FROM user';
$rawData = Yii::app()->db->createCommand($sql);
$count = Yii::app()->db->createCommand('SELECT COUNT(*) FROM (' . $sql . ') as count_alias')->queryScalar();
$model = new CSqlDataProvider($rawData, array(
'keyField' => 'id',
'totalItemCount' => $count,
'sort' => array(
'attributes' => array(
'id','title', 'type'
),
'defaultOrder' => array(
'id' => CSort::SORT_ASC, //default sort value
),
),
'pagination' => array(
'pageSize' => 10,
),
));
$this->render('admin', array(
'model' => $model,
));
}
Admin.php (View file)
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-grid',
'dataProvider'=>$model,
'filter'=>$model,
'columns'=>array(
array('header'=>'firstname','value'=>'$data["firstname"]'),
array('header'=>'lastname','value'=>'$data["lastname"]'),
array('header'=>'username','value'=>'$data["username"]'),
),
)); ?>

how to apply sorting on model method in CGridView Yii

I have User model which contain a function that calculates the average revenue per user. Now i want apply sorting in CGridView on the column which is associated with getAvgRevenue() function. While license is relation in the User model.
Here is my code,
public class User{
$user_id;
$email;
public function getAvgRevenue(){
$count = 0;
$revenue = 0;
foreach ($this->license as $license){
$revenue += $license->price;
$count++;
}
if($count!= 0){
$averageRevenue = $revenue/$count;
return $averageRevenue;
}
else{
return null;
}
}
}
In Controller
$modelUser = new CActiveDataProvider('User', array(
'sort' => array(
'attributes' => array(
'user_id',
'email',
'averagerevenue'
),
'defaultOrder' => array(
'user_id' => CSort::SORT_ASC,
),
),
));
In view
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'user-grid',
'dataProvider' => $modelUser,
'columns' => array(
array(
'header' => 'User ID',
'name' => 'user_id',
),
array(
'header' => 'Email',
'name' => 'email',
),
array(
'header'=>'Average Revenue',
'value'=>'$data->averagerevenue',
),
)
));
?>
Sorting is applicable on user_id and email but Average Revenue column is not sortable. how to specify model method in sort() of CActiveDataprovider
Please help me to solve the problem.
Try this:
$modelUser = new CActiveDataProvider('User', array(
'sort' => array(
'attributes' => array(
'user_id',
'email',
'avgRevenue' //here's the change for you
),
'defaultOrder' => array(
'user_id' => CSort::SORT_ASC,
),
),
));
And your gridview column should be:
array(
'header'=>'Average Revenue',
'value'=>'avgRevenue',
),
and you can read more info on it over here:
http://www.yiiframework.com/wiki/167/understanding-virtual-attributes-and-get-set-methods/

Yii: Can not list data in Grid View

I cant list data in grid using yii framework.My controller is Sitecontroller.php,My view is list_jobseeker.php .I got the error "Fatal error: Call to a member function getData() on a non-object ".Anybody help me?
My controller code
public function actionlist_jobseeker()
{
$session_id=Yii::app()->session['user_id'];
if ($session_id == "")
{
$this->redirect( array('/employee/site/login'));
}
$user_id =$session_id;
$models = Yii::app()->db->createCommand()
->select('*')
->from('job_seeker_profile s')
->join('job_profile j','s.user_id = j.user_id')
->order('s.id')
->queryAll();
$this->render('list_jobseeker',array('models' =>$models));
}
View- list_jobseeker.php
<h1>View Jobseeker</h1>
<div class="flash-success">
</div>
<div class="form">
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'rates-phase-grid',
'htmlOptions' => array('class' => 'table table-striped table-bordered table-hover'),
'dataProvider'=>new CArrayDataProvider($models),
'columns' => array(
array(
'name' => 'Name',
'type' => 'raw',
'value' => 'CHtml::encode($data[*]->name)',
'htmlOptions' => array('style'=>'width:90px;','class'=>'zzz'),
),
array(
'name' => 'Email',
'type' => 'raw',
'value' => 'CHtml::encode($data[*]->email)',
'htmlOptions' => array('style'=>'width:250px;','class'=>'zzz')
),
array(
'name' => 'Password',
'type' => 'raw',
'value' => 'CHtml::encode($data[*]->password)',
'htmlOptions' => array('style'=>'width:90px;','class'=>'zzz')
),
array(
'name' => 'Contact No',
'type' => 'raw',
'value' => 'CHtml::encode($data[*]->contact_no)',
'htmlOptions' => array('style'=>'width:40px;','class'=>'zzz')
),
array(
'name' => 'Gender',
'type' => 'raw',
'value' => 'CHtml::encode($data[*]->gender)',
'htmlOptions' => array('style'=>'width:40px;','class'=>'zzz')
),
array(
'class' =>'CButtonColumn',
'deleteConfirmation'=>'Are you sure you want to delte this item?',
'template'=>'{update}{delete}',
'buttons' =>array('update'=>array(
'label'=>'edit',
'url'=>'Yii::app()->controller->createUrl("UpdateJob",array("id"=>$data["id"]))',
),
'delete'=>array('label'=>'delete',
'url'=>'Yii::app()->controller->createUrl("DeleteJob",array("id"=>$data["id"]))'),
)
)
),
));
?>
dataProvider should be a CDataProvider instance. You are passing in an array: $model. You could wrap this in a CArrayDataProvider:
'dataProvider' => new CArrayDataProvider($model),
A couple of other issues:
a) Your gridview expects $data to be an object and not an array. Either alter all $data->* instances to $data[*] or use CActiveDataProvider and the CActiveRecord instance for the job_seeker_profile table
b) By convention $model usually refers to a single CModel instance. Your array should therefore be named something else in plural e.g $items
I use this:
$data = ...::model()->findAll();
$dataProvider=new CArrayDataProvider('Class of your object');
$dataProvider->setData($data);
$dataProvider->keyField = "primary key of your model";
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
...
array( 'class'=>'CButtonColumn',
'template' => '{ver}',
'buttons' => array(
'ver' => array(
'url'=>'"?id=".$data["..."]',
'imageUrl'=> Yii::app()->baseUrl.'/images/view.png', //Image URL of the button.
),
)
),

Categories