Using yii2's gridview with a normal array of data - php

I have an array of data very similar to this
[
'name'=>'mark',
'age'=> '21'
'height'=> '190 cm'
]
I searched Google and all the results i found were using an active record object.
How do i use the gridview with an array of this sort?

You should use ArrayDataProvider (https://github.com/yiisoft/yii2/blob/master/framework/data/ArrayDataProvider.php)
$provider = new ArrayDataProvider([
'allModels' => $yourArray,
'sort' => [
'attributes' => ['id', 'username', 'email'],
],
'pagination' => [
'pageSize' => 10,
],
]);

Related

Create Associative Array with Foreach, Insert into existing Associative Array

Hello.
I currently have a problem with the AWS Route-53 API. To create a record you need to call a function, which itself needs an array of inputs.
I want to create a record set here and for that I have some POST values. One of them, $_POST['record_value'], is a textarea and has multiple lines. I loop through them. This is to enable multiple values for one record. The code is as follows when you hardcode it as one value in ResourceRecords;
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
[
'Value' => $recordValue
],
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
Hower. I want to make ResourceRecords dynamically. For every line in the textarea I need a new set of the following part of the code;
[
'Value' => $recordValue
],
What I thought is the following;
$newData = [];
foreach(explode("\r\n", $recordValue) as $valLine) {
$newData[] = ["Value" => $valLine];
}
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
$newData
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
However, this seems to return an exception: Found 1 error while validating the input provided for the ChangeResourceRecordSets operation:↵[ChangeBatch][Changes][0][ResourceRecordSet][ResourceRecords][0] must be an associative array. Found array(1).
Am I building the array wrong or am I doing this wrong alltogether?
$newData is already an array, you don't need to wrap it in another array.
'ResourceRecords' => $newData,

Yii 2 - Class 'CArrayDataProvider' not found

I'm new at yii and trying to find my way around. I have done a tutorial or two. I then decided to start editing/changing the example to allow me to learn more. I created a page that does a simple PING. That gets validated. On success, it loads a static page. This all works.
What I wanted to do next is to see how I can utilize a grid to populate that with some data. My real life example is the same. I will get a array of data coming in.
It seems that CArrayDataProvider is what I need. So, I am trying to get a very simple example to work. If I get this to work, I can move on.
I have tried a whole bunch of examples. The error is the same every time. It seems that I do not have CArrayDataProvider installed? If that is even possible.
I did a standard basic install:
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
I have the following at the beginning of my controllers file:
use yii2\data\ArrayDataProvider;
I get no error here.
I searched for the file itself on the file system, could not find it. I did find ArrayDataProvider, so I tried that, same result:
use vendor\yiisoft\yii2\data\ArrayDataProvider;
The error is:
PHP Fatal Error – yii\base\ErrorException
Class 'CArrayDataProvider' not found
This is on line 24:
"dataProvider = new CArrayDataProvider($fruits);"
Here is my example code. Not that I think the issue is in here, but to show what I am trying to do:
$fruits = array(
array('id' => 1, 'name'=>'apple', 'color' => 'green'),
array('id' => 2, 'name'=>'orange', 'color' => 'orange'),
array('id' => 3, 'name'=>'banana', 'color' => 'yellow'),
array('id' => 4, 'name'=>'pineapple', 'color' => 'brown')
);
$dataProvider = new CArrayDataProvider($fruits);
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'fruits-grid',
'dataProvider' => $dataProvider ,
'columns' => array(
array(
'name' => 'ID',
'value' => '$data["id"]',
),
array(
'name' => 'Name',
'value' => '$data["name"]'
),
array(
'name' => 'Color',
'value' => '$data["color"]'
),
)
));
On the file-system (linux) itself I did a update:
composer update
I have been Googling for the last 2 days and I am finding nothing.
I tried adding a date picket. That worked. I used:
https://www.tutorialspoint.com/yii/yii_extensions.htm
So in short, the static page that I call, now displays a DateTimePicker.
At the start of the file I added:
use kartik\datetime\DateTimePicker;
And in the body:
<?php
echo DateTimePicker::widget([
'name' => 'dp_1',
'type' => DateTimePicker::TYPE_INPUT,
'value' => '23-Feb-1982 10:10',
'pluginOptions' => [
'autoclose'=>true,
'format' => 'dd-M-yyyy hh:ii'
]
]);
?>
How do I get yii2 to allow me to use ArrayDataProvider. Or how do I install the extension? Or who do I reference it?
In Yii2 there's not a CArrayDataProvider. Use ArrayDataProvider, like described in docs:
$provider = new yii\data\ArrayDataProvider([
'allModels' => $query->from('post')->all(),
'sort' => [
'attributes' => ['id', 'username', 'email'],
],
'pagination' => [
'pageSize' => 10,
],
]);
Pretty well documented here.
Yii2 supports ArrayDataProvider and yii 1.* supports CArrayDataProvider, so as per your code you are using Yii2, so just replace the below line with
$dataProvider = new CArrayDataProvider($fruits);
With this:
$dataProvider = new ArrayDataProvider($fruits);
Thx to everyone's help! I now have a working example.
In case anyone else has the same issues, I will post my working code here:
use kartik\grid\GridView;
$resultData = [
array("id"=>1,"name"=>"Cyrus","email"=>"risus#consequatdolorvitae.org"),
array("id"=>2,"name"=>"Justin","email"=>"ac.facilisis.facilisis#at.ca"),
array("id"=>3,"name"=>"Mason","email"=>"in.cursus.et#arcuacorci.ca"),
array("id"=>4,"name"=>"Fulton","email"=>"a#faucibusorciluctus.edu"),
array("id"=>5,"name"=>"Neville","email"=>"eleifend#consequatlectus.com"),
array("id"=>6,"name"=>"Jasper","email"=>"lectus.justo#miAliquam.com"),
array("id"=>7,"name"=>"Neville","email"=>"Morbi.non.sapien#dapibusquam.org"),
array("id"=>8,"name"=>"Neville","email"=>"condimentum.eget#egestas.edu"),
array("id"=>9,"name"=>"Ronan","email"=>"orci.adipiscing#interdumligulaeu.com"),
array("id"=>10,"name"=>"Raphael","email"=>"nec.tempus#commodohendrerit.co.uk"),
];
$dataProvider = new \yii\data\ArrayDataProvider([
'key'=>'id',
'allModels' => $resultData,
'sort' => [
'attributes' => ['id', 'name', 'email'],
],
]);
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
[
'attribute' => 'name',
'value' => 'name',
],
[
"attribute" => "email",
'value' => 'email',
]
]
]);

Zend Framework collection validation

I am using Zend Framework 3 and I'm trying to validate a form with a collection field.
My form has a field
$this->add([
'name' => 'domains',
'options' => [
'target_element' => [
'type' => Text::class
]
],
'type' => Collection::class
]);
When I submit the form I obtain something like this as POST data
[
'domains' => [
0 => 'first'
1 => 'second'
]
]
I am trying to validate this with a CollectionInputFilter like the following
$filter = new InputFilter();
$filter->add([
'type' => CollectionInputFilter::class,
'options' => [
'input_filter' => [
'validators' => [
[
'name' => Hostname::class
]
]
]
]
], 'domains');
$filter->setData($data);
but I obtain the exception Zend\InputFilter\CollectionInputFilter::setData expects each item in a collection to be an array or Traversable; invalid item in collection of type string detected.
What am I doing wrong?
I found out that the error was in using CollectionInputFilter. I should have been using ArrayInput instead.

Yii2 and sort in ArrayDataProvider

I am using ArrayDataProvider and i want to know how to make the sort links in view like a
$sort->link('date')
in yii/data/Sort
Follow this (yii\data\sort) and this (yii\data\ArrayDataProvider) documentation
what you can do is make sort like this:
$sort = new Sort([
'attributes' => [
'age',
'name' => [
'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
// or any other attribute
],
]);
after that you can put it in your array data provider
$query = new Query;
$provider = new ArrayDataProvider([
'allModels' => $query->from('post')->all(),
'sort' => $sort, // HERE is your $sort
'pagination' => [
'pageSize' => 10,
],
]);
// get the posts in the current page
$posts = $provider->getModels();
and finally in your view:
// any attribute you defined in your sort defination
echo $sort->link('name') . ' | ' . $sort->link('age');

An issue with Yii2 pager(showing fewer records than should)

I have a problem with Yii2 pagination. I use ListView widget to show data. Also I am using SetSort in my model to sort data.
My search model code:
public function search($params)
{
$query = Items::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'defaultOrder' => ['position' => SORT_ASC],
'attributes' => [
'position' => [
'asc' => ['items.is_top'=>SORT_ASC,'items.position' => SORT_DESC],
'label' => 'By popularity',
],
'pricerup' => [
'asc' => ['prices.price' => SORT_ASC],
'label' => 'Exprensive to cheap'
],
'pricerdown' => [
'asc' => ['prices.price' => SORT_DESC],
'label' => 'Cheap to expensive'
],
]
]);
if (!($this->load($params) && $this->validate())) {
$query->joinWith(['prices']);
return $dataProvider;
}
$query->andFilterWhere([
'discount' => $this->discount,
'present_id' => $this->present_id,
'is_top' => $this->is_top,
'manufacturer_id' => $this->manufacturer_id,
]);
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'description', $this->description])
->andFilterWhere(['like', 'taste', $this->taste])
->andFilterWhere(['like', 'country', $this->country])
->andFilterWhere(['like', 'slug', $this->slug])
->andFilterWhere(['like', 'short_desc', $this->short_desc])
->andFilterWhere(['like', 'thumbnail', $this->thumbnail]);
return $dataProvider;
}
I know that this is not a very good decision to divide DESC and ASC logic for price, but this is needed for current design. My controller code:
public function actionIndex()
{
$searchModel = new ItemsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());
return $this->render('index', [
'dataProvider'=>$dataProvider,
'searchModel'=>$searchModel,
]);
}
As I said, in view I use ListView. This is my view code:
<? Pjax::begin(['id' => 'items', 'clientOptions' => ['method' => 'POST']]);?>
<?
$dataProvider->pagination = [
'defaultPageSize' => 8,
];
echo ListView::widget( [
'id'=>'items',
'pager' => [
'firstPageLabel' => "",
'disabledPageCssClass'=>'swiper-button-disabled',
'lastPageLabel' => "",
'nextPageLabel' => ">",
'prevPageLabel' => "<",
'maxButtonCount'=>0,
'nextPageCssClass'=>'total-button-next', 'prevPageCssClass'=>'total-button-prev',
'options'=>['id'=>'poplinks','class'=>'col-md-12 total-slider-orders margin-right-null padding-left-right-yes total-down-arrow']
],
'dataProvider' => $dataProvider,
'itemView' => '_item',
'summary'=>'',
] );
Pjax::end();?>
As a result I get something like this:
As you can see, it doesn't have last element on the first page, on the next pages everything is ok. I think that this is something with the offset,limit. Can someone tell me, where is an error? Thanks!
Because of many relation, AR show item with two prices as two items, so it show 7 items on page instead of 8. Resolved it just by adding to search model one line:
$query->groupBy('items.id');

Categories