ArrayDataProvider gridview yii2 - yii2

I have this
public function actionIndex()
{
$data = order::getSome();
$dataProvider = new ArrayDataProvider([
'allModels' => $data,
'sort' => [
'attributes' => ['paid']
]
]);
return $this->render('index',['dataProvider' =>$dataProvider]);
}
If in gridview delete 'columns'=> [, there is post all columns in data correct. If in 'columns'=> [ put names of columns, there is '0' in all columns. How to display specific columns?
`public static function getSome(){
return Yii::$app->getDb()->createCommand(
"SELECT order_customFields.order_customFields_delivery_method,
sum(case `order`.order_status when 'paid' then 1 else 0 end) paid,
sum(case `order`.order_status when 'later' then 1 else 0 end) later,
sum(case `order`.order_status when 'delivery-approved' then 1 else 0 end) deliveryapproved,
FROM order_customFields
INNER JOIN `order` ON order_customFields.order_id = `order`.order_id
WHERE
order_customFields.order_customFields_order_date >= '2016-12-01' AND
order_customFields.order_customFields_order_date <= '2016-12-31'
AND order_customFields.order_customFields_delivery_method is not null
GROUP BY
order_customFields.order_customFields_delivery_method"
)->queryAll();
}`

based on your sample could be you are using an activeRecord Order (and not order)
Order::getSome();
this function give you the related models so why you are not use the canonical way for yii2 like
/**
* Lists all AntigoneResidente models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new OrderSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('#common/views/antigone-residente/index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
then in gridview you can access to specific column
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'your_column_name1',
'your_column_name2',
.....
['class' => 'yii\grid\ActionColumn',],
],
]); ?>

If you want to use arrayDataProvider then you have to pass data in array format not in object
public function actionIndex()
{
$data = order::getSome()->asArray();
$dataProvider = new ArrayDataProvider([
'key'=>'id',
'allModels' => $data,
'sort' => [
'attributes' => ['id','paid','vendorid','orderno'],
],
]);
}
In your Gridview
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'paid',
'vendorid',
'orderno'
],
]
]);

Related

Order my consulting by field of my contain

I want order by proyecto_id who is in my ProyectosCategoraisTareas and also order by my categoria id, this is my contain Tareas.Categorias.
I try this but not work.
$proyectostareas = $this->ProyectosCategoriasTareas
->find('all', [
'contain' => [
'Proyectos',
'Tareas',
'Tareas.Categorias' => [
'order' => [
'Tarea.Categoria.id' => 'DESC'
]
]
]
])
->where([
'activa' => '1'
])
->order([
'proyecto_id' => 'DESC'
]);
Try this:
$proyectostareas = $this->ProyectosCategoriasTareas
->find('all')
->where([
'activa' => '1'
])
->join([
'Proyectos',
'Tareas'])
->order([
'proyecto_id DESC',
'Tarea.Categoria.id DESC'
]);

How to use date format to get month and year in Yii2

Let's say I have a table
Date Item Qty
15/1/2016 Item1 10
16/1/2016 Item1 20
16/2/2016 Item1 30
18/2/2016 Item1 10
And In the report I want to display like this
Month Qty
01-2016 30
02-2016 40
Please tell me how can I do this in Yii2.
I've tried the following in my SearchModel.
$query = Productsalesdetails::find()
->select(['DATE_FORMAT(date, "%m-%Y"),productname,sum(total) as total'])
->groupBy('DATE_FORMAT(date, "%m-%Y")');
For the query use letteral select and alias for date_format too..
$query = Productsalesdetails::find()
->select( 'DATE_FORMAT(date, "%m-%Y") as m_date, productname, sum(total) as total')
->groupBy ('m_date, productname');
Do the fact you have already the format in select you can use the alias in attributes
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summaryOptions' => ['class' =>'dfenx_pagination_summary',],
'pager' => ['options' => ['class'=> 'pagination pull-right']],
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => '',
'label' => 'Month',
'value' => function ($model) {
return $model->m_date;
},
],
[
'attribute' => 'productname',
'label' => 'Item',
],
[
'attribute' => '',
'label' => 'Total',
'value' => function ($model) {
return $model->total;
},
],
....
]);
this should work without adding $var in model for alias ..
otherwise you your model you need
class YourModel extends \yii\db\ActiveRecord
{
public $m_date;
public $total;
.....

How to join three tables and get value in grid view

I have three tables :
contacts hasMany groups
contact_groups hasMany contacts
contact_contact_groups
columns in table contact
contact_id | contact_name
columns in table contact_groups
group_id | group_name
columns in table contact_contact_groups
contact_contact_group_id | contact_id | group_id
MODEL
contacs model
public function getContactContactGroups()
{
return $this->hasMany(ContactContactGroups::className(),
['contact_id' => 'contact_id']);
}
contact_groups model
public function getContactContactGroups()
{
return $this->hasMany(ContactContactGroups::className(),
['group_id' => 'group_id']);
}
contact_contact_groups model
public function getGroup()
{
return $this->hasOne(ContactGroups::className(), ['group_id' => 'group_id']);
}
public function getContact()
{
return $this->hasOne(Contacts::className(), ['contact_id' => 'contact_id']);
}
I want to display grid like this :
-----------------------------
Contact Name | Group Name
-----------------------------
Me | Uncategorized
Mother | Family
Jhon | Business
VIEW
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'tableOptions' =>['class' => 'table table-striped table-bordered'],
'columns' => [
[
'attribute' => 'contact_name',
'value' => 'contact_name',
],
[
'attribute' => 'contactContactGroups.group_id',
'value' => 'contactContactGroups.group.group_name',
'filter' => Html::activeDropDownList($searchModel, 'group_id', ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(), 'group_id', 'group_name'),['class'=>'form-control','prompt' => 'Select Group']),
],
],]);
?>
ContactsController
public function actionIndex() {
$this->unsetThisButton(array(4,5));
$searchModel = new ContactsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
But it showing (not set) not a group_name .
A simple way is based on adding a getter in your model eg: for contact_contact_groups model
you have a relation
public function getGroup()
{
return $this->hasOne(ContactGroups::className(), ['group_id' => 'group_id']);
}
use a getter for group_name
public function getGroup_group_name() {
return $this->group->group_name;
}
and in grid view in the attribute
[
'attribute' => 'group_group_name',
'filter' => Html::activeDropDownList($searchModel, 'group_id', ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(), 'group_id', 'group_name'),['class'=>'form-control','prompt' => 'Select Group']),
],
do the same for the relation and field
I Found simple stuff like this :)
GRID (VIEW)
[
'attribute' => 'contactContactGroups.group_id',
'value'=>function ($data) {
$d = array();
foreach ($data->contactContactGroups as $k=>$m)
{
$d[] = ContactContactGroups::get_group_name_by_id($m->group_id);
}
return implode($d, ', ');
},
'filter' => Html::activeDropDownList($searchModel, 'group_id', ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(), 'group_id', 'group_name'),['class'=>'form-control','prompt' => 'Select Group']),
],
models/ContactContactGroups.php Model
I create function get_group_name_by_id($id)
public static function get_group_name_by_id($id){
$model = ContactGroups::find()->where(["group_id" => $id])->one();
if(!empty($model)){
return $model->group_name;
}
return null;
}
so the result is :
Contact | Category
-------------------------------
Me | Business, Family
Erick | Business, Office
Jhon | Office
Thank's #scaisEdge, you give me some clue ;)

Yii2 default sorting is not working

I need to do default sorting by id, we don't show id in grid that's why default sorting is not working here is my code for sorting
public function search($params)
{
$this->load($params);
$query = new \yii\db\Query;
$expression = new \yii\db\Expression('CASE WHEN b.status = 1 THEN "Active" WHEN b.status = 2 THEN "Inactive" END AS status');
$query->select(['b.image','bl.name',$expression,'b.brand_id'])
->from('brand AS b')
->join('INNER JOIN',
'brand_lang AS bl',
'bl.brand_id = b.brand_id AND lang_id = 1');
$query->andFilterWhere([
'status' => $this->status,
]);
$query->andFilterWhere(['like', 'name', $this->name]);
$command = $query->createCommand();
$data = $command->queryAll();
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => $query,
'totalCount' => count($data),
'sort' => [
'attributes' => [
'name' => [
'asc' => ['name' => SORT_ASC, 'name' => SORT_ASC],
'desc' => ['name' => SORT_DESC, 'name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
'status' => [
'asc' => ['status' => SORT_ASC, 'status' => SORT_ASC],
'desc' => ['status' => SORT_DESC, 'status' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Status',
],
'brand_id' => [
'asc' => ['brand_id' => SORT_ASC, 'brand_id' => SORT_ASC],
'desc' => ['brand_id' => SORT_DESC, 'brand_id' => SORT_DESC],
'default' => SORT_ASC,
'label' => 'Brand',
],
'defaultOrder' => ['brand_id' => SORT_ASC]
],
],
'pagination' => [
'pageSize' => 20,
],
]);
return $dataProvider;
}
Can anyone please tell me what is solution for this ? I did lots of googling but didn't success
Your defaultOrder param should be in sort, not in attributes :
'sort' => [
'attributes' => [...],
'defaultOrder' => ['brand_id' => SORT_ASC],
],
Use $dataProvider->sort->attributes['attribute_name']:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => ['brand_id' => SORT_ASC]
],
]);
$dataProvider->sort->attributes['name'] = [
'asc' => ['name' => SORT_ASC],
'desc' => ['name' => SORT_DESC],
];

How to transform this array in a json?

I have this relation CompanyhasMany Branch
And using $this->Company->find('all') output this:
(int) 1 => array(
'Company' => array(
'id' => '4',
'nome' => 'Somov',
'diretores' => 'Marcelo, Carl'
),
'Branch' => array(
(int) 0 => array(
'id' => '3',
'nome' => 'Serra',
'rua' => 'Rua teste 2 exttttt',
'numero' => '22',
'estado' => 'ES',
'cidade' => 'Etc',
'cep' => '',
'responsavel' => '',
'company_id' => '4',
'cnpj' => ''
)
)
),
(int) 2 => array(
'Company' => array(
'id' => '5',
'nome' => 'Soimpex',
'diretores' => ''
),
'Branch' => array()
)
)
I want to transform this in a json like this to use with Highchart:
[{
name: NAME OF COMPANY (nome),
data: NUMBER OF BRANCHS
}, {
name: NAME OF COMPANY (nome),
data: NUMBER OF BRANCHS
}]
How I do this convertion? Thanks
This will return a json object with only one result.
If we use previous example, can be done like this:
$arr = $this->Company->find('all'); // fetch the array
$arr1 = array();
foreach ($arr as $value) {
$tmp = array();
$tmp['name'] = $value['Company']['nome'];
$tmp['data'] = count($value['Branch']);
$arr1[] = $tmp;
}
return json_encode($arr1);
<?php
$sql=mysql_query("select * from Posts limit 20");
$response = array();
$posts = array();
while($row=mysql_fetch_array($sql))
{
$title=$row['title'];
$url=$row['url'];
$posts[] = array('title'=> $title, 'url'=> $url);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
?>
This will generate a file called results.json file where your php file is stored on your online server, taking url and title variables from your MySQL db, you can change the variable names to what you want to fetch.
The whole idea is about like this
$arr=$this->Company->find('all'); // fetch the array
$arr1=array();
foreach ($arr as $value) {
$arr1['name']=$value['Company']['nome'];
//some more manual transform to desire format
}
return json_encode($arr1);