How to add looping in DetailView Yii2? - php

Ok, this maybe simple. I want to add looping in my DetailView in Yii2.
Example :
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'attribute' => 'atasan',
'value' => /*I want to add looping here*/
],
],
]) ?>
How can I do that? Thank you for your answers :)

Since version 2.0.11 value can be an annonymous function aswell, so:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'attribute' => 'atasan',
'value' => function($model) {
$example = '';
foreach($model->atasan as $atasan) {
//here your stuff
$example .= 'Oh God, it looped again. ';
}
return $example; // here's returned value
}
],
],
]) ?>
Just remember, that this anonymous function should return a value, not echo or anything.

Related

How to pass the database data and display it in yii2 highCharts?

I have install the miloschuman\highcharts\Highcharts, website : https://www.yiiframework.com/extension/yii2-highcharts-widget. I have a database with the table columns lme_price and lme_name which I want to display the price of the copper in the highcharts. I'm using PHP.
Below is my code which I have done. This is the code in my models. I create a static function with the query inside it to find the data that I want from the database.
public static function getCopperPrice()
{
$getCopperPrices = Lme::find()
->select('lme_price')
->where(['lme_name' => 'LME Copper'])
->all();
return $getCopperPrices;
}
Here is my code in the view. I have a table show in the view which show every data from the database.
<div class="lme_index">
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'searchModel'=> $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label'=> 'DATE',
'attribute' => 'lme_title',
],
[
'label'=> 'MATERIAL',
'attribute'=> 'lme_name',
],
[
'label'=> 'PRICE (US$)',
'attribute'=> 'lme_price',
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Here is the code for the highcharts graph.
<div class = "graph">
<?= Highcharts::widget([
'options' => [
'title' => ['text' => 'Copper Price'],
'xAxis' => [
'categories' => []
],
'yAxis' => [
'title' => ['text' => 'Price $US']
],
'plotOption' => [
'series' => [
['name' => 'Copper',
'data' => [lme::getCopperPrices()]],
]
]
]
]);?>
I want to display only 1 material price in the highcharts. I call the function from the model inside the series but the graph shows nothing on it. The coding there didn't show any error to me.
Can someone help me or tell me how to solve this? Thanks.
Chart require integer values to display
public static function getCopperPrice()
{
$cooperPrices = [];
$copperPriceList = Lme::find()
->select('lme_price')
->where(['lme_name' => 'LME Copper'])
->column();
foreach($copperPriceList as $price) {
$cooperPrices[] = (int) price;
}
return $cooperPrices;
}

How to Add Filter Search Like Grid View In List View Yii2

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]);

How to show has many relation record in Yii2 GridView and DetailView?

I want to show staff has many hobbies from table hobbies in detail view and gridview.
But I got an error exception Trying to get property of non-object
Here's my schema code model:
app\model\TblDataStaff
....
public function getTblDataHobis()
{
return $this->hasMany(TblDataHobies::className(), ['id_staff' => 'id']);
}
view code: view.
<?= DetailView::widget([
'model' => $model,
'attributes' => [
...
['attribute'=>'namHob','value'=>$model->tblDataHobis->id],
...
],
]) ?>
index:
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
......
['attribute'=>'namHob','value'=>function($namHob){return $namHob->tblDataHobis->name_hobby;},],
.....
['class' => 'yii\grid\ActionColumn'],
],]);?>
How to show many hobbies of staff ?
Nothing strange, you have a Trying to get property of non-object error simply because $model->tblDataHobis return an array of TblDataHobies objects.
You could simply try this :
// display hobbies names separated with commas
echo implode(', ', \yii\helpers\ArrayHelper::map($model->tblDataHobis, 'id', 'name_hobby'));
For DetailView :
'value' => implode(\yii\helpers\ArrayHelper::map($model->tblDataHobis, 'id', 'name_hobby')),
For GridView :
'value' => function($model) {
return implode(\yii\helpers\ArrayHelper::map($model->tblDataHobis, 'id', 'name_hobby')),
},
Try with:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'header' => 'number of hobbies',
'value' => function($data) {
return $data->getTblDataHobis()->count();
}
]
]) ?>
Just get the item data, and after that create a simple yii2 query.
For example my 'worker' has city id, with this id we can find city name by this id.
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'name:ntext',
'surname:ntext',
'fathers',
[
'attribute' => 'city_id',
'value'=> function($data){
$city = City::find()->where(['id'=>$data->city_id])->one();
$info = $city->name;
return $info;
},
'format'=>'html',
],
'status',
'street',
'in_company',
],
]) ?>

Using 2 gridviews with different models of same class Yii2 independently

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 ..

Yii2 DetailView: value of attribute using a function [duplicate]

This question already has answers here:
Changing value of an attribute in DetailView widget
(2 answers)
Closed 6 years ago.
I get an error when I use a function to get the value of an attribute and it's working normally using Gridview. What I'm doing wrong?
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'label' => 'subject_type',
'value' => function ($data) {
return Lookup::item("SubjectType", $data->subject_type);
},
'filter' => Lookup::items('SubjectType'),
],
'id',
'subject_nature',
],
]) ?>
I have experienced this kind of problem. The error was
PHP Warning – yii\base\ErrorException
htmlspecialchars() expects parameter 1 to be string, object given
what I did was transfer the function in the model like this.
function functionName($data) {
return Lookup::item("SubjectType", $data->subject_type);
},
and then in your view.php file..
[
'label'=>'subject_type',
'value'=>$model->functionName($data),
],
Just use call_user_func()
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'label' => 'subject_type',
'value' => call_user_func(function ($data) {
return Lookup::item("SubjectType", $data->subject_type);
}, $model),
'filter' => Lookup::items('SubjectType'),
],
'id',
'subject_nature',
],
]) ?>
Fabrizio Caldarelli, on 05 January 2015 - 03:53 PM, said:
Yes because 'value' attribute is a real value or attribute name, as doc says
So your code should be:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'label' => 'subject_type',
'value' => Lookup::item("SubjectType", $model->subject_type),
'filter' => Lookup::items('SubjectType'),
],
'id',
'subject_nature',
],
]) ?>

Categories