i have a new question yii2.
how to show relational values from other tables in gridview in views/viewname/index and also add a button to that for confirm?
thank you
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\LaptopSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Laptops';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="laptop-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Laptop', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'network',
'technology',
'sup_id',
'speaker',
// 'optical_drive',
// 'webcam',
// 'touchpad',
// 'card_reader',
// 'ethernet',
// 'vga',
// 'hdmi',
// 'usb3_ports',
// 'usb2_ports',
// 'usb_type_c',
// 'thunderbolt_ports',
// 'serial_ports',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
how to add here new attributes and also add a button?
for get the related values you can add to your model
a function for the relation
public function getYourRelatedModel()
{
return $this->hasOne(YourRelatedModel::className(), ['id' => 'your_id_fk']);
}
and the add a getter for the field you need
public function getYour_field() {
return $this->yourRelatedModel->your_field;
}
and last add to your gridview the column
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'network',
'technology',
'sup_id',
'speaker',
'your_field',
how to show relational values from other tables in gridview
Consider order and customer model
In order, model establishes the customer relationship.
public function getCustomer()
{
return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
}
Show customer name in order listing page
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label' => 'Customer',
'attribute' => 'customer_id',
'value' => function($data) {
return $data->customer->name;
},
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
is there any way to make sortby link for that?
Add "attribute" to grid column it resolves the sortable problem
[
'value'=> 'customer.name',
'label' => 'Customer Name',
],
try this for showing name of customer!
if you want to sort this you need to create in searchModel a customerName fake attribute and work with it.
Related
I have this in my controller departments class:
Hello guys
So there is something i am trying to achieve with yii
I have a Departments table and a student table. Inside the students view i want to show the departments name and the filter.
While i am able to display the department name for each student but the department name filter doesn't show.
Below is my code with comments:
/*Begining of Students model*/
class Students extends \yii\db\ActiveRecord
/* this is where i did a reference to my students table*/
public function getDepartments()
{
return $this->hasMany(Departments::className(), ['department_id' => 'ID']);
}
--- End of Students model
--- Begining of Students View
/*Inside my view folder i have the Students folder where i have an index.php file where everything is listed in Gridview. */
View/Students/index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\ArrayHelper;
use app\models\States;
use kartik\export\ExportMenu;
/* #var $this yii\web\View */
/* #var $searchModel app\models\AgentsSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Agents';
$this->params['breadcrumbs'][] = $this->title;
$gridColumns = [
['class' => 'yii\grid\SerialColumn'],
'created_at',
'name',
departments.name',
'status',
['class' => 'yii\grid\ActionColumn'],
];
// Renders a export dropdown menu
echo ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns
]);
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'tableOptions' =>['class'=>'table table-bordered'],
'filterModel' => $searchModel,
'columns' => $gridColumns
]); ?>
</div>
/*End of Students view*/
/*Begining of Students search.*/
/*models/StudentsSearch.php*/
I understand that the code below inside my StudentsSearch.php file is responsible for displaying the filter for each field.
public function rules()
{
return [
[['phone'], 'integer'],
//my understanding is that this is what controls the filter form, only fields listed here have filters
[['phone','name' 'email', 'address','city','departments.name'], 'safe'],
];
}
/*End of Students search.*/
I am able to show filter for every other thing but how do i show filter for the department name?
read this: https://www.yiiframework.com/wiki/851/yii2-gridview-sorting-and-searching-with-a-junction-table-columnmany-to-many-relationship
add a new property to your StudentsSearch, e.g. $departmentName
add this property to StudentsSearch's rules, e.g. [['departmentName'], 'safe']
use 'departmentName' in your query, e.g. $query->andFilterWhere(['like', 'department.name', $this->departmentName])
sorting on a calculated field works similar, read this: https://www.yiiframework.com/wiki/621/filter-sort-by-calculatedrelated-fields-in-gridview-yii-2-0
$dataProvider->setSort([
'attributes' => [
'id',
'departmentName' => [
'asc' => ['department.name' => SORT_ASC],
'desc' => ['department.name' => SORT_DESC],
'label' => 'Department',
'default' => SORT_ASC
],
]
]);
in the studentsSearch class add department to the rules.
Make reference to the Departments table by adding it to the rules.
public function rules()
{
return [
//this controls the filter section, only fields listed here will have filter
[['Department'], 'safe'],
];
}
Then in Students view in this case in my index.php i add the attribute "departments" and make reference to the deparment name using departments.name in my gridColumns
$gridColumns = [
['class' => 'yii\grid\SerialColumn'],
'name',
'email:email',
'address',
[
'attribute' => 'departments',
'label' => Department Name',
'value' => 'department.name'
],
'status',
['class' => 'yii\grid\ActionColumn'],
];
?>
in students model inside your attributeLabels method add the departments.name attribute.
public function attributeLabels()
{
'Department.name' => 'Department Name'
}
I have a Table KHDN references table Loaihinh via foreign key loaihinh_ten
Table Loaihinh:
ten int identity primary key; //
loai varchar(100);
Table KHDN:
...fields
loaihinh_ten: foreign key references Loaihinh(ten)
What should i do if i want to show Loaihinh. loai instead of the foreign key loaihinh_ten in khdn/views.php Yii2:
<?php
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model common\models\Khdn */
?>
<div class="khdn-view">
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'ten:ntext',
'chudautu:ntext',
'ngaybatdau:ntext',
'ngayhoanthanh:ntext',
'giatri:ntext',
'trangthai_ten',
'diachi:ntext',
'ghichu:ntext',
'loaihinh_ten',
],
]) ?>
</div>
thanks you so much!!
Use
$model->relationName->fieldName
Example:
/**
* #return \yii\db\ActiveQuery
*/
public function getLoaihinh()
{
return $this->hasOne(KHDN::className(), ['id' =>
'loaihinh_ten']);
}
Then use the following relation in View:
$model->loaihinh->loai;
There are many method of doing this things. you can use any of the following methods for this problem.
you need not to use joinWith method for this you can get that relation data any where in your program just using
$model->relation_name_decleared_in_model
below is the sample code that is use a
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'type',
'value' => function ($model) {
return \app\models\BlockType::getConstantMessage($model->type);
},
],
[
'class' => 'kartik\grid\EditableColumn',
'header' => 'POSITION',
'attribute' => 'position',
],
[
'attribute' => 'access',
'value' => function ($model) {
return \app\components\Helper::ACCESS[$model->access];
},
],
'some_attribute',
[
'attribute' => 'other_relation',
'value' => 'model.relation.column'
],
[
'attribute' => 'Page',
'value' => function ($model) {
return $model->page->pageContent->name;
},
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
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 created a Global Search with grid view displaying, but this is the problem for the first time that the search page loads or when the search field is empty and you search, all the data in the db will be displayed.
and I have used the _search.php view inside another view.
_search view:
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'globalSearch') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
the main view:
<?php echo $this->render("../ads/_search", ['model' => $model]); ?>
<?php Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $model,
'showOnEmpty' => false,
'summary' => '',
'showFooter' => false,
'showHeader' => false,
'columns' => [
'name',
'type',
'explanation',
'address',
'province_name',
'cost',
],
]);?>
<?php Pjax::end(); ?>
Anything else is needed? Let me know.
If you want to display the grid, let the filter model return a data provider with no results when global search is empty
class FilterModel extends Model {
public $globalSearch;
::
::
public function search($params) {
$provider = new ActiveDataProvider(
$query = SomeModel::find();
);
if (!$this->globalSearch) {
$query->where('1=0'); // returns no results
return $provider;
}
// other code to return results with filter applied
::
::
return $provider;
}
}
I don't know how you applied this globalSearch filter, but this is default behavior of grid filters: when filters not defined - GridView will display matched data items (=== all items).
But if you want change this behavior you can simply not render GridView in the case of empty filter:
<?php echo $this->render("../ads/_search", ['model' => $model]); ?>
<?php
if(!empty($model->globalSearch)){
Pjax::begin();
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $model,
'showOnEmpty'=>false,
'summary'=>'',
'showFooter'=>false,
'showHeader' => false,
'columns' => [
'name',
'type',
'explanation',
'address',
'province_name',
'cost',
],
]);
Pjax::end();
}
?>
Using gii, I created a model based on a database table and then CRUD for the model. One of the columns is showing either 1 or 2 as they are stored in the database. To create new, it was easy using a ActiveForm->dropDownList() widget:
<?= $form->field($model, 'type')->dropDownList(['1'=>'Role', '2'=>'Permission'], ['prompt'=>'Select Auth Item Type']) ?>
How to use GridView and show Role instead of 1 and Permission instead 2?
In gridview you can use value
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
.........
[
'attribute' => 'type',
'label' => 'Type',
'format' => 'raw',
'value' => function ($model) {
if ( $model->type == 1) {
return 'Role';
} else {
return 'Permission';
}
},
],