i want to display array in view form but i don't know how ?
can any one help me :
my controller code is :
$query = new Query;
$query
->select(['Day_Name'])
->from('days')
->join( 'INNER JOIN','doctorsworkday','doctorsworkday.Day_id =days.dayid');
$command = $query->createCommand();
$dataProvider = $command->queryAll();
$dataProvider= array($dataProvider);
return $this->render('view',
[
'model' => $this->findModel($id),
'days'=>$days,
'doctorsworkday'=>$doctorsworkday,
'dataProvider' => $dataProvider,
])
my view code is :
<?=
DetailView::widget([
'model' => $dataProvider,
'attributes' => [
'Day_Name'
],
])
?>
but its shows : (not set)
when i use vat_dump($dataProvider) there is an array .. but i don't know how to show it
enter Var_Dump
Well firstly you are using a DetailView for displaying multiple results. DetailView is used to display the detail of a single data model as said in the docs. You could use a GridView to display multiple results. GridView accepts a dataProvider not an array so you'll need to turn your array into a dataProvider.
fortunately you can use the class ArrayDataProvider to do just that:
$gridViewDataProvider = new \yii\data\ArrayDataProvider([
'allModels' => $dataProvider,
'sort' => [
'attributes' => ['Day_Name'],
],
'pagination' => ['pageSize' => 10]
]);
something like this should work.
Then you pass this $gridViewDataProvider to the gridview like this:
<?= GridView::widget([
'dataProvider' => $gridViewDataProvider,
'columns' => [
'name'
]
]) ?>
Also note that in your controller you wrapped your $dataProvider in an array with this line:
$dataProvider= array($dataProvider);
You should remove that line and then everything should work as far as I can tell.
Related
I Want to Add Filter With List View (Some Thing Like What Is In Grid View) but I Don Not Know How Do That
Filters I Want Are CheckBox And DropDown Options.
Here Is My Action Code In SiteController
<?php
public function actionMobiles(){
$searchModel = new MobileSearch();
//$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider = new ActiveDataProvider([
'query' => Mobile::find(),
'pagination' => [
'pageSize' => 1,
],
]);
// get the posts in the current page
//$posts = $dataProvider->getModels();
return $this->render('mobiles', ['dataProvider' => $dataProvider,'searchModel' => $searchModel]);
}
?>
In View File I Have 2 Files :
Here Is mobiles View :
<?php
use yii\widgets\ListView;
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\ArrayHelper ;
use app\models\Mobile;
?>
<?= ListView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'itemView' => '_mobiles',
]); ?>
And In _mobiles I Have :
<?php
use yii\widgets\DetailView;
?>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
//'id',
'id',
'title',
//'ativo',
],
]) ?>
It Shows Data From DataBase Correctly With It Pagination.
But How To Add Filter To Update List(CheckBox And DropDown List Are Use to Update)??
here is the code for you, you should replace attribute and model name according to yours.
[
'attribute' => 'attribute_name',
'label' => 'Email',
'value' => function($model){
return $model->attribute_name;
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => \yii\helpers\ArrayHelper::map([Your Model]::find()->asArray()->all(), 'id', 'email'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Email', 'id' => 'grid--search-email']
],
Add this line in your view file,
Just above listview widget
echo $this->render('_search', ['model' => $searchModel]);
I have a view that shows 2 gridviews of the same model class, however, they seem to use the same filter, sort and pagination, even though they use different search models and dataProviders like so:
In the controller:
public function actionIndex()
{
$searchModel = new CasoAccionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageParam = "tarea-propia-page";
$dataProvider->sort->sortParam = "tarea-propia-sort";
$searchModelTerceros = new CasoAccionSearch();
$dataProviderTerceros = $searchModelTerceros->search(Yii::$app->request->queryParams);
$dataProviderTerceros->pagination->pageParam = "tarea-3ros-page";
$dataProviderTerceros->sort->sortParam = "tarea-3ros-sort";
return $this->render('myIndex', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'searchModelTerceros' => $searchModelTerceros,
'dataProviderTerceros' => $dataProviderTerceros,
]);
}
And in the view:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
// ['class' => 'yii\grid\SerialColumn'],
'acc_referencia',
'acc_fecha_accion',
'fecha_creacion',
[
'label' => 'Creado Por',
'format' => 'raw',
'value' => function($data){
return $data->abCreador->nombreCompleto;
}
],
//'ab_creacion',
[
'label' => 'Caso',
'format' => 'raw',
'value' => function($data){
return Html::a($data->caso->caso_nombre,
Yii::$app->urlManager->createUrl(['caso/view','id'=>$data->caso_id]));
}
],
// 'caso.caso_nombre',
'acc_descripcion:ntext',
'caso.caso_referencia',
[
'label' => 'Cliente',
'format' => 'raw',
'value' => function($data){
return Html::a($data->caso->cliente->nombreCliente,
Yii::$app->urlManager->createUrl(['cliente/view','id'=>$data->caso->cl_id]));
}
],
// 'resp_id',
// 'acc_tipo',
// 'estado',
// 'acc_horas_estimadas',
// 'acc_horas_ejecutadas',
// 'acc_fecha_accion',
// 'acc_descripcion:ntext',
// 'fecha_creacion',
// 'ab_creacion',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?= GridView::widget([
'dataProvider' => $dataProviderTerceros,
'filterModel' => $searchModelTerceros,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'acc_referencia',
'acc_fecha_accion',
'fecha_creacion',
'caso.caso_nombre',
[
'label' => 'Responsable',
'format' => 'raw',
'value' => function($data){
return $data->abResponsable->nombreCompleto;
}
],
//'abResponsable.ab_nombres',
'acc_descripcion:ntext',
'caso.caso_referencia',
[
'label' => 'Cliente',
'format' => 'raw',
'value' => function($data){
return Html::a($data->caso->cliente->nombreCliente,
Yii::$app->urlManager->createUrl(['cliente/view','id'=>$data->caso->cl_id]));
}
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Any ideas about how to make them behave independently?
I see you have already configured different pagination and sorting parameters for both models. That is correct, so all you need to fix is filtering.
Your filtering applies to both grids, because your form element names are the same. Your search model has the formName() method, which returns a string. By default, it returns class name. So, when you try to filter on acc_referencia in any of the forms, the following parameter is added to your url: CasoAccionSearch[acc_referencia]. It is then picked up by both grids which is not your desired behavior. What you should make instead is grid1[acc_referencia] for first grid and grid2[acc_referencia] for second grid.
You have two choices here: either implement CasoAccionSearch::formName() in such a way that it returns two different form names for two different instances of CasoAccionSearch, or just use two different search models.
I suggest you do it this way:
class CasoAccionSearch
{
public $formNameParam = 'CasoAccionSearch';
// ...
// other attributes
public function formName()
{
return $this->formNameParam;
}
// ...
// other methods
}
And then in your view:
$searchModel = new CasoAccionSearch(['formNameParam' => 'grid1']);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
For consistency, I would also make pageParam and sortParam attributes of CasoAccionSearch that get passed to the data provider in search().
They use the same class CasoAccionSearch() and then the same search function .. if you need two separated function you need a proper search function eg:
class CasoAccionSearch extends CasoAccion
{
.....
public function search($params)
{
.......
}
public function search2($params) // searc for second grid
{
.......
}
and the adapt you controller/action code for use the two different search function ..
I want to ask you about using Grid View in Yii2. In my web, i want to pass parameter from controller to gridview and i use it for GET parameter.
My Controller:
$sql = "SELECT * FROM adikbinaan WHERE adikbinaan.jenjang_id = $jenjang";
$n = count(CariAdikBinaan::findBySql($sql)->all());
$adikbinaan = new SqlDataProvider([
'sql' => $sql,
'totalCount' => $n,
'sort' => [
'attributes' => [
'ADIKBINAAN_NAMALENGKAP',
],
],
'pagination' => [
'pageSize' => 20,
],
]);
$adik = new CariAdikBinaan();
return $this->render('index', [
'dataProvider' => $adikbinaan,
'data' => $adik,
]);
My View
<?= GridView::widget([
'dataProvider' => $dataProvider,
'layout'=>"{pager}\n{items}\n{summary}",
'showFooter'=>true,
'showHeader'=>true,
'showOnEmpty'=>false,
'columns' => [
'ADIKBINAAN_NAMALENGKAP',
'ADIKBINAAN_TEMPATLAHIR',
'ADIKBINAAN_TANGGALLAHIR',
[
'label'=>'Aksi',
'format' => 'raw',
'value'=>function ($data) {
return Html::a(Html::encode("Lihat"),'adikbinaan/view?id='.$data->ADIKBINAAN_ID);
},
],
],
]); ?>
And i get "Trying to get property of non-object" in return Html::a(Html::encode("Lihat"),'adikbinaan/view?id='.$data->ADIKBINAAN_ID);
It looks like Action Column but i don't want to use it.
How do i fix it?
data is an array not an object. From the API page for SQLDataProvider:
SqlDataProvider provides data in terms of arrays, each representing a row of query result.
Therefore your code should read
return Html::a(Html::encode("Lihat"), 'adikbinaan/view?id='.$data['ADIKBINAAN_ID']);
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 have two database tables 'user' and 'role'. I used Yii framework 2.0 Gii to create CRUD with User model and UserSearch model. By default, Gii uses GridView::widget for the index page for the 'user' model.
In the search($params) method inside of the UserSearch model, I used the following code to join the above tables together
$query = User::find()->with('role');
Everything works fine with the query.
By default Gii does not include the data from the joined table 'role' in the GridView::widget inside of the views/user/index.php page. With the join query above I could retrieve data from both tables. In the views/user/index.php page I have injected the GridView::widget with the following code so that it also includes the data and column names from the joined table (role).
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'userid',
'username',
'role.role_name',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Everything works fine with the role data 'role_name included in the GridView::widget. But the problem is that there is no search box for the role_name. The GridView::widget creates search box for the User properties only. Is there any way to add search box for the properties of the joined table 'role' because I also would like to search through 'role_name' as well as through other properties of the User model.
Try this way:
In your UserSearch model add
UserSearch extends ...
{
public $roleFilterInputName; //the name of the filter search input
//important
function rules()
{
//add roleFilterInputName as safe
return [
[['xxx', 'roleFilterInputName'], 'safe'], //!!!!
];
}
}
in your grid:
'columns':
[
//...
[
'attribute' => 'roleFilterInputName',
'value' => 'role.role_name'
],
//...
]
in UserSearch::search()
$query->andFilterWhere(['like', 'role.role_name', $this->roleFilterInputName])
But I guess you'll have to use 'joinWith' instead of 'with'.
Inside CGridView add below code. It will enable filter with dropDownList.
[
'attribute' => 'act_role_id',
'label' => 'Actor Role',
'value' => 'actRole.role_name',
'filter' => yii\helpers\ArrayHelper::map(app\models\ActorRole::find()->orderBy('role_name')->asArray()->all(),'act_role_id','role_name')
],
CGridView code Snippet is as below:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'userid',
'username',
[
'attribute' => 'act_role_id',
'label' => 'Actor Role',
'value' => 'actRole.role_name',
'filter' => yii\helpers\ArrayHelper::map(app\models\ActorRole::find()->orderBy('role_name')->asArray()->all(),'act_role_id','role_name')
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Try it with
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'userid',
'username',
//'role.role_name',
['attribute' => 'role', 'value' => 'role.role_name'],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
I just have tried it in my code, so I'm not sure if this works also with your code. But if so, I don't know why it has to be defined this way.
I guess the answer of rajesh ujade also includes this definition, however, for Yii 1.
This worked for me
Table = Lead (id , year_id)
Table = Year (id, text)
Added text in lead (index.php)
Year::find()->all() = This code pull all value from table/ all years.
[
'attribute'=> 'year_id',
'format' => 'html',
'value' => 'year.value',
'label' => 'Year',
'filter' => Html::activeDropDownList($searchModel, 'year', yii\helpers\ArrayHelper::map(Year::find()->all(), 'year_id', 'value'), ['class' => 'form-control', 'prompt' => '---']),
],
Also it shows dropdown as well sorting.
image Showing Dropdown in Grdiview
#Ekonoval is going in right way.
Just add following in serch function of UserSearch:
After initializing ActiveDataProvider object like this:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 5,
],
]);
$dataProvider->sort->attributes['roleFilterInputName'] = [
'asc' => ['role.role_name' => SORT_ASC],
'desc' => ['role.role_name' => SORT_DESC]
];
You may write query in your UserSearch model like
if($this->role)
{
$query->join('LEFT JOIN','role','role.user_id = user.id')->andFilterWhere(['role.item_name' => $this->role]);
}