Could an ArrayDataProvider be used as an ActiveDataProvider? - yii2

I'm trying to use fill my listView using an ArrayDataProvider. However the dataProvider consists of Arrays, not objects. I ran into this problem because the category in the model is an id, where I need the name corresponding to that id from another table. Hence I created an Array where the id is the corresponding name.
private function getDataProvider()
{
return new ArrayDataProvider([
'allModels'=>$this->getFaqs(), // returns array of faqs
'sort'=>[
'attributes'=>['id','category','question','answer']],
'pagination'=>[
'pageSize'=>10,
],
]);
}
Here is my ListView widget
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => function($dataProvider, $key, $index, $widget)
{
return Html::a($dataProvider->question,
Url::toRoute(['faq/view', 'id' => $dataProvider->primaryKey]));
}
]);

It works, I use it like this
$dataProvider = new ArrayDataProvider([
'allModels' => [['name' => '0am - 6am'], ['name' => '6am - 9pm'], ['name' => '9am - 12pm'], ['name' => '12pm - 3pm'], ['name' => '3pm - 6pm']],
]);
<?= ListView::widget([
'dataProvider' => $dataProvider,
'layout' => "{items}",
'itemOptions' => ['class' => 'item', 'style' => 'margin-bottom: 5px;'],
'itemView' => function ($model, $key, $index, $widget) use ($transportRun) {
//return print_r($model, true);
return Html::a(Html::encode($model['name']), ['delivery/index', 'DeliverySearch' => ['transport_run' => $transportRun, 'timeslot' => $key]], ['class' => 'btn btn-lg btn-primary btn-block']);
},
]) ?>
ListView and GridView can use any class that implements yii\data\DataProviderInterface. You can take a look here http://www.yiiframework.com/doc-2.0/yii-data-dataproviderinterface.html to see who implements it, so you can use any of those classes on both ListView and GridView.
You should also be able to do a
'allModels'=>$this->faqs, // returns array of faqs

Related

Yii2 multiple ListView in one page

I'm using 2 widgets in one page, Both are using listview, one is for blogs and another one is for pages and both are using ScrollPager. I want to show more button in each separately. The problem is the show more button is shown only for pages but not for blog, if I remove the page widget it will display for blogs. I'm trying to display show more for pages and show more for blogs. I tried by pageParam but the problem still exist.
widget:
class UserPagesWidget extends \yii\base\Widget
{
public $usr_id;
public function run()
{
$dataProviderContent = new ActiveDataProvider([
'query' => Post::find()->Where(['user_id' => $this->usr_id])
->orderBy(['post_crdate' => SORT_DESC]),
'pagination' => [
'pageParam' => 'contentPagination',
'pageSize' => 5,
],
]);
return $this->render('/user/widget/pstList', [
'dataProviderContent' => $dataProviderContent,
]);
}
}
Render file:
<?= ListView::widget([
'dataProvider' => $dataProviderContent,
'summary'=>'',
'itemOptions' => ['class' => 'item'], // LY - FOR ( LOAD MORE )
'emptyText' => 'No Content',
'itemView' => function ($model, $key, $index, $widget) {
return $this->render('/user/profileContent/usr-pst-content',['model' => $model]);
},
'pager' => ['class' => \kop\y2sp\ScrollPager::className()],
]);
?>
Blog Widget:
class UserBlogsWidget extends \yii\base\Widget
{
public $usr_id;
public function run()
{
$dataProviderBlog = new ActiveDataProvider([
'query' => Blog::find()->Where(['user_id' => $this->usr_id])
->orderBy(['blog_update' => SORT_DESC]),
'pagination' => [
'pageParam' => 'blogPagination',
'pageSize' => 6,
],
]);
return $this->render('/user/widget/blgList', [
'dataProviderBlog' => $dataProviderBlog,
]);
}
}
Blog render file:
<?= ListView::widget([
'dataProvider' => $dataProviderBlog,
'summary'=>'',
'itemOptions' => ['class' => 'item'], // LY - FOR ( LOAD MORE )
'emptyText' => 'No Blogs',
'itemView' => function ($model, $key, $index, $widget) {
return $this->render('/user/profileContent/usr-blg-content',['model' => $model]);
},
'pager' => ['class' => \kop\y2sp\ScrollPager::className()],
]);
?>
Both widgets are called in one view file.
<div class="row chn-row">
<div class="col-sm-12" style="padding:15px">
<!-- separing -->
<?= UserPagesWidget::widget(['usr_id' => $model->user_id]) ?>
<!-- separing -->
</div>
<div class="col-sm-12" style="padding:15px">
<?= UserBlogsWidget::widget(['usr_id' => $model->user_id]) ?>
</div>
</div>
The problem is the show more button is displayed only for pages.
You need to adjust selectors to distinguish between two widgets. By default ScrollPager uses some generic selector (.list-view) that will match all list views. You should explicitly set ID for ListView widgets and use it in ScrollPager config as selector for widget initialization.
<?= ListView::widget([
// ...
'dataProvider' => $dataProviderBlog,
'options' => ['id' => 'blog-list-view'],
'pager' => [
'class' => \kop\y2sp\ScrollPager::className(),
'container' => '#blog-list-view',
'paginationSelector' => '#blog-list-view .pagination',
],
]) ?>
<?= ListView::widget([
// ...
'dataProvider' => $dataProviderContent,
'options' => ['id' => 'content-list-view'],
'pager' => [
'class' => \kop\y2sp\ScrollPager::className(),
'container' => '#content-list-view',
'paginationSelector' => '#content-list-view .pagination',
],
]) ?>
See https://kop.github.io/yii2-scroll-pager/#general-options

Searching records for date fails

Following code should search records for date. But whatever I click,main branch in condition will be executed,so I will get outprinting:
choice_date is false
It will be searched for records which are <=department_created_date,but never for records >=department_created_date
Any ideas,how to fix this?
Here is my RadioList
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\widgets\ActiveForm;
$this->title = Yii::t('app', 'Departments');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="departments-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php
$form = ActiveForm::begin();
$model = new backend\models\DepartmentsSearch();
?><?= $form->field($model, 'choice_date')->radioList(array(0 => 'Before', 1 => 'After'))->label('Please, choose Datesearching!'); ?>
<p><?= Html::a(Yii::t('app', 'Create Departments'), ['create'], ['class' => 'btn btn-success']) ?></p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'branches_branch_id',
'label' => Yii::t('app', 'Branch'),
'value' => function($model) {
if ($model->branches_branch_id) {
return $model->branchesBranch->branch_name;
} else {
return NULL;
}
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => backend\models\Branches::getBranchList(),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Branch', 'id' => 'grid-Branch-search-rechtsart']
],
'branchesBranch.branch_name',
'department_name',
[
'attribute' => 'companies_company_id',
'label' => Yii::t('app', 'Company'),
'value' => function($model) {
if ($model->companies_company_id) {
return $model->companiesCompany->company_name;
} else {
return NULL;
}
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => backend\models\Companies::getCompanyList(),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Company', 'id' => 'grid-Company-search-rechtsart']
],
'department_created_date',
['class' => 'yii\grid\ActionColumn'],
],
]);
?>
</div>
and here is my searching class:
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Departments;
class DepartmentsSearch extends Departments {
public $choice_date;
public function rules() {
return [
[['department_id'], 'integer'],
[['choice_date'], 'boolean'],
[['department_name', 'department_created_date', 'department_status', 'companies_company_id', 'branches_branch_id'], 'safe'],
];
}
public function scenarios() {
return Model::scenarios();
}
public function search($params) {
$query = Departments::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate())
return $dataProvider;
/*
Whatever I click in RadioList,property will be 0,so I'll get setFlash->'choice_date is false'
*/
if ($this->choice_date == 0) {
Yii::$app->session->setFlash('If-branch is false', 'choce_date is false');
$query->andFilterWhere(['<=', 'department_created_date', $this->department_created_date]);
} else {
Yii::$app->session->setFlash('if-branch is true', 'choice_date is true');
$query->andFilterWhere(['>=', 'department_created_date', $this->department_created_date]);
}
$query->joinWith('companiesCompany');
$query->joinWith('branchesBranch');
$query->andFilterWhere(['like', 'department_name', $this->department_name])
->andFilterWhere(['like', 'companies.company_name', $this->companies_company_id])
->andFilterWhere(['like', 'branches.branch_name', $this->branches_branch_id])
->andFilterWhere(['like', 'department_status', $this->department_status]);
return $dataProvider;
}
}
Further ideas,how to fix this misery?
P.S.: For Bizley's help, here is an extraction of my controller:
class DepartmentsController extends Controller{
public function actionIndex(){
$searchModel = new DepartmentsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
further methods are irrelevant,here. Why will property of date-record not be rendered in view?
}
Your $model in the view is RadioForm so the form sends this field as RadioForm[choice_date].
But you are expecting choice_date from DepartmentsSearch model and this field is left empty.
Remove the RadioForm model, it's totally unneeded. Use DepartmentsSearch model in the form view.
Update:
Since OP finally told that this is a GridView I can update my answer to suit him.
There is filterSelector property in GridView you can use - you can set there additional jQuery selectors that will be used for filtering.
Here is updated code with comments below:
<?php $form = ActiveForm::begin();
echo $form->field($searchModel /* 1 */, 'choice_date')->radioList([
0 => 'Before', 1 => 'After'
], ['itemOptions' => ['class' => 'choiceRadio' /* 2 */]])->label('Please, choose Datesearching!');
ActiveForm::end(); /* 3 */ ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'filterSelector' => '.choiceRadio', /* 4 */
// ...
This is the $searchModel I was talking about. You don't need any other model here.
You can set here any CSS class you want, it's for filterSelector.
Don't forget to close form like you did in your original code.
This is the selector for the radio input. Mind the notation - . for CSS class, # for CSS id.

Two gridview from two model search by single field in yii2

I have one search form with a field and a button. On the button click I want to search 2 searchmodel - sellitembtdtSearch and puritembtdtSearch. The result will be shown in one view. I can display the view without any problem. The problem is when I'm searching only one searchmodel is getting searched. Please let me know how can I search both the searchModel at the sametime.
First I land on index2.php page where the form is.
'action' => ['/stock/sellitem/printproductledger3',],
'method' => 'get',
<?= $form->field($model, 'productname')->textInput(['maxlength' => true,]) ?>
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
actionIndex2.php
public function actionIndex2()
{
$searchModel1 = new SellitemsbdtSearch();
$dataProvider1 = $searchModel1->search(Yii::$app->request->queryParams);
$searchModel2 = new PuritemsbdtSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
return $this->render('_formbtdt', [
'model' => $searchModel2,
//'searchModel1' => $searchModel2,
]);
}
public function actionPrintproductledger3() {
$searchModel1 = new SellitemsbdtSearch();
$dataProvider1 = $searchModel1->search(Yii::$app->request->get());
$searchModel2 = new PuritemsbdtSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->get());
//$productname = yii::$app->request->get('productname');
//$prodesc = yii::$app->request->get('prodesc');
$content = $this->renderPartial('_printproductledgerbtdt', [
//'productname' => $productname,
'searchModel1' => $searchModel1,
'dataProvider1' => $dataProvider1,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
//'prodesc' => $prodesc,
]);
return $this->render('_printproductledgerbtdt', [
'dataProvider1' => $dataProvider1,
'searchModel1' => $searchModel1,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
This code only searchs puritemdtdtSearch. I want to search puritembtdtSearch and sellitembtdtSearch at the same time. Thanks.
The issue is you are using searchModel2 in your form so you are just getting the result of searchModel2. And not getting the result of searchModel1.
What you can do is send searchModel1 to your _search file.
<?php echo $this->render('_search', ['model1' => $searchModel1, 'model2' => $searchModel2]); ?>
Now in your form use a hidden input.
<?php echo $form->field($model1, 'productName')->textInput(['id' => 'model1']); ?>
<?php echo $form->field($model2, 'prodcutName')->hiddenInput(array('id' => 'model2')); ?>
Now its that we have two model fields we need to populate the hidden field, this can be done using jquery.
<?php $this->registerJs('
//add the .search class name for your search button
jQuery("body").on("click", ".search", function() {
alert("Hello");
var a = $("#model1").val();
$("#model2").attr("value", a);
});
');?>
Try this..tested completely and works fine!!

yii2 kartik export menu - No results found

Using karktik export menu only. Why do the following exports an excel file with no results found.. I am sure that there are records inside the TblDv model. But in the excel it says no records found.
-in the controller
public function actionExport(){
$provider = new ActiveDataProvider([
'query' => TblDv::find(),
'pagination' => [
'pageSize' => 20,
],
]);
return $this->render('export', [
'dataProvider' => $provider,
]);
}
-the view
<?php
use kartik\export\ExportMenu;
use kartik\grid\GridView;
use kartik\helpers\Html;
$gridColumns = [
'id',
];
echo ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns,
'fontAwesome' => true,
]);
?>
I dont know why but it worked when I changed the gridcolumns to this..
$gridColumns=[
['class' => 'yii\grid\SerialColumn'],
'id',
];

How to connect 3 tables in yii2 and display in Gridview then make sorting work correctly

I have used the gii tool to create crud application. I have 3 tables the tbl_targetcities, lib_cities, and lib_provinces. I was able to connect lib_cities to tbl_targetciteis but not the lib_provinces. And also the sorting of city / Municipality does not work. It seems that it sorts according ti the ID.
tbl_target_cities
lib_cities
lib_provinces
sample View
So far here is my relation in the model.
public function getCityName()
{
return $this->hasOne(LibCities::className(),['city_code'=>'city_code']);
}
in my view file...
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'city_code',
'value'=>'cityName.city_name'
],
[
'attribute'=>'prov code',
'value'=>'cityName.city_name'
],
'kc_classification',
'cluster',
'grouping',
'priority',
'launch_year',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
How to display the prov_name from lib_provinces???
EDIT to answer user2839376 question in the comment box
IN THE SEARCH MODEL CLASS
$query = TblSpBub::find();
$query->joinWith('brgyCode')->joinWith(['cityCode'])->joinWith(['cityCode.provCode']);
$covered= LibAreas::find()->where(['user_id'=>yii::$app->user->identity->id])->all();
$query->all();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['id'=>SORT_DESC]],
]);
$dataProvider->sort->attributes['city'] = [
'asc' => ['lib_Cities.city_name' => SORT_ASC],
'desc' => ['lib_Cities.city_name' => SORT_DESC],
];
$dataProvider->sort->attributes['province'] = [
'asc' => ['lib_provinces.prov_name' => SORT_ASC],
'desc' => ['lib_provinces.prov_name' => SORT_DESC],
];
In LibCities model add new relation:
public function getProvince()
{
return $this->hasOne(LibProvince::className(),['prov_code'=>'prov_code']);
}
And change getCityName relation. You should add with() for relation:
public function getCityName()
{
return $this->hasOne(LibCities::className(),['city_code'=>'city_code'])->with(['province']);
}
And in view correct your columnto this:
[
'attribute'=>'prov code',
'value'=>'cityName.province.prov_name'
],
You have to use the function relations() in models.
In tbl_target_cities model:
public function relations()
{
return array(
'city' => array(self::HAS_ONE, 'LibCities', 'city_code'),
);
}
In LibCities model :
public function relations()
{
return array(
'province' => array(self::HAS_ONE, 'LibProvinces', 'prov_code'),
'targets' => array(self::HAS_MANY, 'TargetCity', 'city_code',
);
}
This will allowed you to jump throw the LibCities model,
now you can simply acces to prov name like this :
$model->city->province->prov name;
Note : You need to have the 3 models defined.
EDIT
array(
'name' => 'province name',
'value' => $data->city->province->prov_name;
),
Done it, Heres how.
in addition to the above code (original post)
// in Model I added an additional function
public function getTaskowner()
{
return $this->hasOne(Tasks::className(), ['id' => 'task_id'])
->with(
['location','taskowner']
);
}
and in view i did this
....
'columns' => [
....
[
'class' => 'kartik\grid\DataColumn',
'value'=> 'tasks.location.taskowner.name',
.....
],
.....
and it worked
key points. used an array with the 'with->(..)' to include both then in the view added 'tasks.location.taskowner.name', to join them all