Dataprovider to EExcelView - yii

lets say i have a table named
cars{
'id','name','brand_id',
}
and another table
brand{
'id','brand_name',
}
I have a situation that i want to generate an Excel report with the following attributes.
'name','brand_name' i.e. SELECT cars.name, brand.brand_name FROM cars INNER JOIN on brand WHERE cars.brand_id = brand.id
So i created a dataprovider like this:
$sql = "SELECT cars.name, brand.brand_name FROM cars INNER JOIN brand on cars.brand_id = brand.id";
$result = Yii::app()->db->createCommand($sql)->queryAll();
$this->render('doc', array('dataprovider' => $result));
Now i want to generate Excel file with result as a dataProvider so i write the following code:
// lets say i am doing this in view page named doc.php
$factory = new CWidgetFactory();
Yii::import('ext.eexcelview.EExcelView',true);
$widget = $factory->createWidget($this,'EExcelView', array(
'dataProvider'=>$dataprovider->search(),
'grid_mode'=>'export',
'title'=>'Title',
'creator'=>'TNC',
'autoWidth'=>false,
'filename'=>'Report.xlsx',
'stream'=>false,
'disablePaging'=>false,
'exportType'=>'Excel2007',
'columns'=>array(
'name',
'brand_name',),
'showTableOnEmpty' => false,
));
$widget->init();
$widget->run();
I have included all the extensions that i have to.. This code is working when i fed the dataProvider field with a single table entry .
But the situation arises when i include multiple tables.

These lines don't actually make a dataprovider:
$result = Yii::app()->db->createCommand($sql)->queryAll();
$this->render('doc', array('dataprovider' => $result));
You'll want to do something like the following:
$dataprovider = new CSqlDataProvider($sql, array(
'pagination'=>false,
);
$this->render('doc', array('dataprovider' => $dataprover);
More info here: http://www.yiiframework.com/doc/api/1.1/CSqlDataProvider

This works for 2 tables, dont know works for more than 2 or not.
$dataProvider = new CArrayDataProvider($dataprovider, array('id' => 'brand', 'sort' => array('attributes' => array('brand_name', ), ), 'pagination' => false));
$this -> render('doc', array('dataprovider' => $dataProvider,));

Related

How to link Yii's Active Record model table with other table using JOIN

I am using Yii 2.
I have model User with table in DB.
I tried link this table with table auth_assignment which has columns user_id, item_name and created_at using LEFT JOIN clause. I wrote this:
$model = User::find()->leftJoin('auth_assignment AS a', '`a`.`user_id` = `user`.`id`');
Then I attach $model to ActiveDataProvider:
$dataProvider = new ActiveDataProvider([
'query' => $model,
'pagination' => [
'pageSize' => 5,
],
]);
But when I run application it prints only Users columns: screenshot
What I do wrong?
In User model you can't get attributes of another table(auth_assignment ).
You can do it by two ways.
Define relationship between User and auth_assignment table in User model using hasOne()
Example : ( use your model name for auth_assignment table)
public function getAuth()
{
return $this->hasOne(Authassignment::className(), ['id' => 'user_id']);
}
Than you can use auth_assignment table attributes as $model->auth->user_id;
Generate query as array as below, in this scenario you don't need to define relationship in model.
$model = User::find()
->select('user.*,a*')
->leftJoin('auth_assignment AS a', 'a.user_id= user.id')
->asArray();
$dataProvider = new ActiveDataProvider([
'query' => $model,
'pagination' => [
'pageSize' => 5,
],
]);
Now you can use attributes as array variable i.e.
$model['user_id'] etc.

Yii, CGridView: filtering and sorting count column from related tables

I have 3 tables: productions, chunks (production may have a lot of chunks, so chunks contains production_id column) and chunk_designers (chunk may have a lot of designers, so chunk_designers has a column chunk_id).
I have to render data from productions in CGridView and add a column: count of chunks (for every production item in table), which are not assigned to any chunk. In other words:
SELECT COUNT(*) FROM `chunks`
left JOIN `chunk_designers`
ON chunks.id = chunk_designers.chunk_id
WHERE production_id = 520 AND chunk_id IS null
...where 520 - dynamic value for every row, productions.id.
ChunkController action:
function actionProductionList() {
$model = new Productions('search');
$model->unsetAttributes(); // clear any default values
$dataProvider = $model->search($_GET);
$dataProvider->criteria->order = 'start_time DESC';
$this->render('production_list', array(
'provider' => $dataProvider,
'model' => $model,
));
}
Model Productions:
class Productions extends AppModel {
....
public $unassignedBlocksCount;
....
public function rules() {
return array(
array('unassignedBlocksCount, id, ...', 'safe'),
array('unassignedBlocksCount, id, ...', 'safe', 'on'=>'search'),
);
}
//in search() I added:
$criteria->compare('unassignedBlocksCount', $this->unassignedBlocksCount, true);
}
And in view:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'menu-grid',
'dataProvider' => $provider,
'filter' => $model,
'enablePagination' => true,
'columns' => array(
array(
'name' => 'unassignedBlocksCount',
'value' => 'Chunks::getUnassignedBlocksCount($data->id)'
),
...
Column data is rendered fine, but when I try to filter it, I get the following error: unknown column unassignedBlocksCount in where clause.
I tried to write in search() method in Productions model:
// subquery to retrieve the count of posts
$count_sql = "(SELECT COUNT(*) FROM `chunks` "
. "LEFT JOIN `chunk_designers` "
. "ON chunks.id = chunk_designers.chunk_id "
. "WHERE production_id = 520 AND chunk_id IS NULL)";
// select
$criteria->select = array(
'*',
$count_sql . " as unassignedBlocksCount",
);
And just added unassignedBlocksCount element in columns in view.
But I still get the same error, when filter, and also problem is that I don't know, how to get production_id in $count_sql dynamically, depending on every table row (that's why in every row for that column value is 1, because it's correct value for production_id = 520).
So, my question is: how to get sortable and filterable column in CGridView, which is calculated (by COUNT()) from data in other tables? Thanks in advance.

Yii data provider with clist view

i want to search multiple models in Yii application. The search result are displayed in CList view. Need to use dataprovider in list view. So how can i use multiple dataprovider in Clist view?
You cannot make use of multiple dataproviders rather you combine the result in a single dataprovider
Something like this to get you started:
public function actionSearch($q) {
// Sanitize input
$q = strtolower(strip_tags($q));
$q = preg_replace('/[^a-z 0-9 _ \- \']/', '', $q);
$model1 = Model1::model()->findAll('title LIKE "%'.$q.'%"');
$model2 = Model2::model()->findAll('title LIKE "%'.$q.'%"');
$rawData = array_merge($model1, $model2);
$dataProvider = new CArrayDataProvider($rawData, array(
'sort'=>array(
'attributes'=>array(
'datePublished DESC', 'title',
),
),
'pagination'=>array(
'pageSize'=>10,
),
));
$this->render('search', array(
'dataProvider' => $dataProvider,
'query' => $q,
));
}

How to sort the fields from relation table in Yii?

I am trying to implement sorting with Yii list view. I have joined 2 tables named provider_favourite and service_request in list view. And the fields and contents from both tables are listing in the list view. But sorting is working only in provider_favourite table, not from service_request table.How can I sort the fields from service_request table? Iam using csort for sorting. I also tried CGrid view. But the same problem is happening in grid view also ..
Iam using the following code to join
$criteria = new CDbCriteria;
$criteria->select = 'favourite_notes,favourite, favourite_added_date,max_budget,preferred_location,service_name';
$criteria->join = 'LEFT JOIN service_request AS s ON service_request_id = favourite';
$criteria->condition = 'favourite_type = 1';
$sort=new CSort('ProviderFavourite');
// $sort->defaultOrder='s.max_budget ';
$sort->applyOrder($criteria);
$sort->attributes = array(
'max_budget' => 'service_request.max_budget',
'service_name' => 'service_request.service_name',
'favourite_added_date'
);
$type = 2;
$data = new CActiveDataProvider('ProviderFavourite', array('criteria' => $criteria, 'pagination' => array('pageSize' => 4),'sort'=>$sort
));
$this->renderPartial('favourites', array(
'ModelInstance' => ProviderFavourite::model()->findAll($criteria),
'dataProvider' => $data, 'type' => $type, 'sort'=>$sort,
));
and also Iam providing sortable attributes in list view
$this->widget('zii.widgets.CListView', array('dataProvider'=>$dataProvider,'itemView'=>'index_1',
'id'=>'request',
'template' => ' {items}{pager}',
'sortableAttributes'=>array('favourite_notes','max_budget','service_name')
));
If more details needed, I will provide. Thanks in advance
You have to specify attributes property of your $sort instance. By default only fields of $modelClass (ProviderFavourite in your case) are sortable.
I think it could look like this (not tested):
$sort->attributes = array(
'service_name' => array(
'asc' => 's.service_name ASC',
'desc' => 's.service_name DESC'
),
// ...another sortable virtual attributes from service_request table
"*"
);
You should not create a CSort object in $sort. The CActiveDataProvider will already provide you with the right sort object. The way you do it, you apply the sort criteria to $criteria before you configure the sort attributes. That can not work.
You should try a simple setup like this instead:
$data = new CActiveDataProvider('ProviderFavourite', array(
'criteria' => $criteria,
'pagination' => array('pageSize' => 4),
'sort'=> array(
'attributes' => array(
'service_name' => array(
'asc' => 's.service_name ASC',
'desc' => 's.service_name DESC'
),
// ...
),
));
If you need to access the related CSort object (which you usually don't if you use a CGridView or CListView, because they deal with that for you), then you get it via $data->sort.

Yii CActiveDataProvider Join and select from joined table

I have the following example code:
$dataProvider = new CActiveDataProvider('firstTable',
array('criteria' => array(
'select' => 't.firstfield,secondTable.secondfield',
'join' => 'join secondTable on secondTable.id=t.secondTable_id',
),
'pagination' => array(
'pageSize' => 10,
),
));
$results=$dataProvider->getData();
After running the code above, firstField (from the model table - firstTable) is available in the object, but secondField (from the joined table - secondTable) is not.
Can anyone provide assistance on what is wrong with the code or why the "select" option is not picking up the secondField?
it would be better if you use CDbCriteria, that has a better solution to join table with the help of relations. I can show the example with CDbCriteria.
$criteria = new CDbCriteria;
$criteria->select = 'firstfield';
$criteria->with = array('secondTable_relation'=>array('select'=>'secondfield'));
$dataProvider = new CActiveDataProvider('firstTable',
array('criteria' => $criteria,
'pagination' => array(
'pageSize' => 10,
),
));
$results=$dataProvider->getData();
secondTable_relation is a relation name with secondTable.
Can anyone provide assistance on what is wrong with the code or why the "select" option is not picking up the secondField?
Answer:
That is happening because you have not selected the field which relates the two tables, i.e the foreign key in firstTable : secondTable_id. So if you do:
'select' => 't.firstfield,t.secondTable_id,secondTable.secondfield',
you will be able to access the secondField of secondTable:
$singleresultrow->secondTableRelationName['secondField'];// a single result row can be obtained by foreach iteration over $results
However there will still be another query (Lazy Loading) when you access the secondField. And the initial(before lazy) object returned will not have the secondTable object filled.
The problem i think lies in the fact that by default yii accesses the related fields by lazy loading, and for that to happen the related foreign_key should be present in the model you are trying to make a dataprovider of, here it is firstTable, and the foreign_key secondTable_id.