I'm really new in Yii2 and I still don't know how to configure it properly. I noticed that the GridView has search fields on each column. What I need now is to create a main/single search field wherein a user can input keywords then results will show in the GridView after hitting the search button.
Is this possible? I also used this Kartik widget in my search form field which has a dropdown list in it. Image here.
We're told to use this dropdown search and when the user inputs some keywords (sometimes returns 'No results found' on the dropdown list), and clicks the Search button, the page will refresh displaying all the results based on the keywords inputted.
I also searched some problems same as mine here in SO, such as these:
Yii2 Search model without using GridView
yii 2 , make an active form text field master search field
I found no luck. The second link doesn't have any answers.
I will include my action controller here in case you need it.
public function actionIndex()
{
$session = Yii::$app->session;
$searchModel = new PayslipTemplateSearch();
$PayslipEmailConfig = PayslipEmailConfig::find()->where(['company_id'=> new \MongoId($session['company_id'])])->one();
$payslipTemplateA = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'A'])->one();
$payslipTemplateB = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'B'])->one();
$pTemplateModel = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->all();
$user = User::find()->where(['_id' => new \MongoId($session['user_id'])])->one();
$module_access = explode(',', $user->module_access);
$dataProvider = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
return $this->render('index', [
'PayslipEmailConfig' => $PayslipEmailConfig,
'dataProvider' => $dataProvider,
'payslipTemplateA' => $payslipTemplateA,
'payslipTemplateB' => $payslipTemplateB,
]);
}
My view, index.php
<?php
$users = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
echo $this->render('_search', ['model' => new User(), 'users' => $users]);
?>
_search.php
<?php $form = ActiveForm::begin([
'action' => ['searchresults'],
'method' => 'get',
'id' => 'searchForm'
]); ?>
<?php
$listData = array();
foreach ($users as $user) {
$listData[(string)$user->_id] = $user->employeeId. ' '.$user->fname.' '.$user->lname;
}
echo $form->field($model, '_id')->widget(Select2::classname(), [
'data' => $listData,
'addon' => [
'append' => [
'content' => Html::button('Search', ['class'=>'btn btn-primary']),
'asButton' => true
]
],
'options' => [ 'class' => 'dropdown-responsive', 'responsive' => true, 'placeholder' => 'Search employee ID or name (e.g. 10015 or John Cruz)', 'id' => 'user_id', 'name' => 'id'],
'pluginOptions' => [
'allowClear' => true,
'responsive' => true
],
]);
?>
<?php ActiveForm::end(); ?>
Really need help for this one.
This example code as per your requirement. so, try it.
User Searchmodel's search() method.
public function search($params)
{
$query = User::find();
$query->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
......
........
}
Controller's actionIndex
public function actionIndex()
{
$session = Yii::$app->session;
/* $searchModel = new PayslipTemplateSearch(); */
$PayslipEmailConfig = PayslipEmailConfig::find()->where(['company_id'=> new \MongoId($session['company_id'])])->one();
$payslipTemplateA = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'A'])->one();
$payslipTemplateB = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'B'])->one();
$pTemplateModel = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->all();
$user = User::find()->where(['_id' => new \MongoId($session['user_id'])])->one();
$module_access = explode(',', $user->module_access);
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
/*
$dataProvider = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
*/
return $this->render('index', [
'PayslipEmailConfig' => $PayslipEmailConfig,
'dataProvider' => $dataProvider,
'payslipTemplateA' => $payslipTemplateA,
'payslipTemplateB' => $payslipTemplateB,
'searchModel' => $searchModel,
]);
}
and index.php
<?php
$users = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
echo $this->render('_search', ['model' => $searchModel, 'users' => $users]);
?>
Related
I am getting my dataProvider from which I try to remove some models that don't meet the wanted criteria. This filter is not SQL related and therefore I can't apply it directly to the query. On my view the pagination links are displayed if I leave the dataprovider just as it was. But after I apply the filters to remove the unwanted models, the pagination links disappear. I have tried setting the pagination on my new dataProvider but nothing works.
Here's my code in the controller action:
$request = Yii::$app->request;
$search_model = new StaffEmploymentListViewSearch();
$data_provider = $search_model->search($request->queryParams);
$models = $data_provider->models;
for($k=0;$k<count($models);$k++)
{
if($models[$k]->employ === null){
unset($models[$k]);
}
}
$config = [
'pageParam' => 'page',
'pageSizeParam' => 'per-page',
'forcePageParam' => true,
'route' => null,
'params' => null,
'urlManager' => null,
'validatePage' => true,
'totalCount' => 5214,
'defaultPageSize' => 20,
'pageSizeLimit' => [
'0' => 1,
'1' => 50
],
'pagesize' => 20
];
$data_provider->setModels($models);
$data_provider->setPagination($config);
return $this->render('all-staff',[
'dataProvider' => $data_provider,
'searchModel' => $search_model
]);
Here's my search method:
$query = StaffEmploymentListView::find()
->SELECT([
'PAYROLL_NO',
'BIRTH_DATE',
"ADD_MONTHS(BIRTH_DATE, 70 * 12) AS RETIRE_DATE"
]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => false,
'pagination' => [
'pagesize' => 20,
],
]);
How do I go about doing this?
Try to use ArrayDataProvider
$query = StaffEmploymentListView::find()
->select([
'PAYROLL_NO',
'BIRTH_DATE',
"ADD_MONTHS(BIRTH_DATE, 70 * 12) AS RETIRE_DATE"
]);
$allModels = [];
foreach ($query->all as $staffEmployment)
{
if ($model->employ === null){
$allModels[] = $model;
}
}
$dataProvider = new ArrayDataProvider([
'allModels' => $allModels,
'pagination' => [
'pageSize' => 20,
],
'sort' => false
]);
return $this->render('all-staff',[
'dataProvider' => $data_provider,
'searchModel' => $search_model // ???
]);
I want to use Select2 dr as filter in Yii Grid view, but it doesn't filter at all, only refreshes the page.
I take the data from 2 tables - from accounts I take only user_id, and from credits I take everything else. And every filter works, except And the 'user_id' one.
<?php
echo GridView::widget(
[
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'attribute' => 'wp_id',
'value' => 'accounts.user_id',
'filter' => Select2::widget(
[
'model' => $searchModel,
'attribute' => 'wp_id',
'data' => ArrayHelper::map(Accounts::find()->all(), 'wp_id', 'user_id'),
'options' => ['placeholder' => ' --Filter by user id-- '],
'language' => 'en',
'pluginOptions' => [
'allowClear' => true,
],
]
),
],
],
]
); ?>
Here is the action in the controller.
<?php
public function actionIndex()
{
$searchModel = new CreditsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
} ?>
And this is the search model method
<?php
public function search($params)
{
$query = Credits::find()->with('accounts');
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
if(!empty($this->user_id)) {
$query->andFilterWhere(['=', 'accounts.user_id', $this->user_id]);
}
// grid filtering conditions
$query->andFilterWhere([
'user_id' => $this->user_id,
'wp_id' => $this->wp_id,
'credits_bought' => $this->credits_bought,
'purchase_date' => $this->purchase_date,
'id' => $this->id,
]);
return $dataProvider;
}
} ?>
Thanks in advance!
Because you are passing the wp_id under the GridView filter and selecting the wp_id from the Accounts model as the value of the select2-dropdown
ArrayHelper::map(Accounts::find()->all(), 'wp_id', 'user_id')
Although it is confusing that you use the gridview column attribute wp_id and use the select2 to filter the user_id for the same column but if you are looking to do that you might need to change the above to
ArrayHelper::map(Accounts::find()->all(), 'user_id', 'wp_id')
I want to use ArrayDataProvider with the following code of siteController. I wrote the following code but it doesn't work.
Here is my actionIndex :
public function actionIndex()
{
$query = new \yii\db\Query;
$query->select('*')->from('business_main_categories');
$query->createCommand();
$dataProviders = [];
foreach ($query as $category) {
$dataProviders[] = new ArrayDataProvider([
'allModels' => $category,
'sort' => false,
'pagination' => false,
]);
}
return $this->render('index', [
'dataProvider' => $dataProviders,
]);
}
And want it to iterate in gridView. So, I wrote the following code (I don't know whether it's correct or not) :
Here is my index.php :
<?php
$dataProviders[] = 'dataProvider';
foreach ($dataProviders as $dataProvider) {
echo GridView::widget([
'dataProvider' => $dataProvider,
'summary' => '',
'columns' => [
[
'attribute' => 'bmc_image',
'format' => 'html',
'label' => '',
'value' => function ($data) {
return Html::img($data['bmc_image'],
['width' => '210px', 'height' => '190px']);
},
],
]
]);
}
?>
Controller
public function actionIndex()
{
$query = new \yii\db\Query;
$dataProvider = new ArrayDataProvider([
'allModels' =>$query->from('business_main_categories')->all(),
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
}
Index
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'bmc_image',
'format' => 'html',
'value' => function ($data) {
return Html::img($data['bmc_image'],['width' => '210px', 'height' => '190px']);
},
],
],
]); ?>
I solved my problem without using gridview. As follows -
My SiteController -
public function actionIndex()
{
$searchModel = new BusinessMainCategoriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageSize = $dataProvider->getTotalCount(); //-1 : disable
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
using this code I get all records in dataProvider from my db.
(Note that, I'm using ActiveDataProvider in my 'BusinessMainCategoriesSearch' model)
And, my index.php is -
<?php
$m = $dataProvider->getModels();
foreach ($m as $dp) {
echo "<img src = '".$dp['bmc_image']."' />";
echo '<center><font color = "white">'.$dp['bmc_name'].'<font/></center>';
}
?>
It worked great for me & it's a easiest way to do so.
Greetings
I want to display data from my Atividades model in Yii2
My AtividadesController has the following code for actionView2
public function actionView2()
{
$query = new Query;
$dataProvider = new ActiveDataProvider([
'query' => $query->from('Atividades'),
'pagination' => [
'pageSize' => 20,
],
]);
// get the posts in the current page
$posts = $dataProvider->getModels();
return $this->render('view2', ['dataProvider' => $dataProvider, 'posts' => $posts]);
}
And in my View 2 i have the following List View that appears with the message showing 4 of 4 items, but doesn't shows the items
<?= ListView::widget([
'dataProvider' => $dataProvider,
]); ?>
In Y1.xx i had a property called 'attributes' for display the model fields
How can i display the model fileds in Yii2 inside this Listview
Many thanks in advance
I have solved it by myself :)
It was not hard
In my View2 Written the following code
<?= ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_view2',
]); ?>
And then duplicated an original view file, changed its name to _view2, put it in the same folder, and style it has needed
In my ActividadesController changed the actionView2 code to:
public function actionView2()
{
$dataProvider = new ActiveDataProvider([
'query' => Atividades::find(),
'pagination' => [
'pageSize' => 20,
],
]);
// get the posts in the current page
$posts = $dataProvider->getModels();
return $this->render('view2', ['dataProvider' => $dataProvider]);
}
_View2 code
<?= DetailView::widget([
'model' => $model,
'attributes' => [
//'id',
'atividade',
'descricao:ntext',
//'ativo',
],
]) ?>
SOLVED
I was searching how to create pager in Yii2 using LinkPage widget.
Is there any example? I am new in Yii, so any help would be good.
It is simple
$dataProvider = new ActiveDataProvider([
'query' => User::find(),
'pagination' => array('pageSize' => 50),
]);
echo \yii\widgets\LinkPager::widget([
'pagination'=>$dataProvider->pagination,
]);
Or if you don't use dataProvider you should use this:
$query = User::find();
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>30]);
echo \yii\widgets\LinkPager::widget([
'pagination' => $pagination,
]);
In controller:
function actionIndex()
{
$query = Article::find()->where(['status' => 1]);
$countQuery = clone $query;
$pages = new Pagination(['totalCount' => $countQuery->count()]);
$models = $query->offset($pages->offset)
->limit($pages->limit)
->all();
return $this->render('index', [
'models' => $models,
'pages' => $pages,
]);
}
In view file:
foreach ($models as $model) {
// display $model here
}
// display pagination
echo LinkPager::widget([
'pagination' => $pages,
]);
Below is too simple for adding pagination,
We just need to add in controller,
$dataProvider = new ActiveDataProvider([
'query' => Post::find(),
'pagination' => [
'pageSize' => 20,
],
]);
Yii2 will bring pagination on index page,
https://yii2-framework.readthedocs.io/en/stable/guide/output-data-widgets/
In your controller
$searchModel = new CourseModuleMasterSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination = ['pageSize' => 20];//add this line