yii2 get name instead of id - php

hi i have this weird problem. i had a table relation. and i want to view the related table field name instead of id.
here is my model:
public function getQCat()
{
return $this->hasOne(QbCategory::className(), ['id' => 'q_cat']);
}
here is my view:
<?php echo DetailView::widget([
'model' => $model,
'attributes' => [
'q_cat',
'question:ntext',
'q_c1:ntext',
'q_c2:ntext',
'q_c3:ntext',
'q_c4:ntext',
'q_ans:ntext',
],
]) ?>
that 'q_cat' field in view i want to display name instead of id. i tried using 'q_cat.name' but it says (not set).
thanks.

assuming you QbCategory model is
id
name
and you want accessing to QbCategory value in your Main Class
you could access to the attribute name in this way
in Main class
add relation
public function geQcat()
{
return $this->hasOne(QbCategory::className(),
['id' => 'qcat_id']); // qcat_id is the column name in Main class that join QCat to Main
then you can build a getter for for QbCategory name
public function getQcatname() {
return $this->qcat->name; // name is the name of name column in QCat
}
then in your Main Clals Detail View
<?php echo DetailView::widget([
'model' => $model,
'attributes' => [
'qcatname', // this i the ref for getQcatname function in Main Model
'question:ntext',
'q_c1:ntext',
'q_c2:ntext',
'q_c3:ntext',
'q_c4:ntext',
'q_ans:ntext',
],
]) ?>

Easier solution
[
'attribute' => 'q_cat',
'value => $model->Qcat->qcat_name
]

Related

yii2 Gridview does not show column with joined attributes

I have a model Certificates which has a foreign key application_id of another model called Application. So each certificate belongs to the single application.
Now there is a situation where I would like to show all the certificates of the existing user. The user id exist inside the application model like user_id.
This is the query
SELECT * FROM `certificates`
inner join applications b ON
application_id = b.id where b.user_id = 7
Now based on the records coming from the above query I would like to show some columns of the certificates and some from the applications using grid view. But for some reasons, if records are more than one then I don't get any column data from the application.
<?php Pjax::begin(); ?> <?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'application_id',
'verified_application_file_path',
'certificate_name',
'application.name',
'application.user_id',
[
'attribute' => 'creation_date',
'format' => ['date', 'php:d/m/Y']
],
[
'attribute' => 'expiry_date',
'format' => ['date', 'php:d/m/Y']
],
],
]); ?>
<?php Pjax::end(); ?></div>
The above grid shows name and user id if a single record get return otherwise it shows "Not set". I Am not sure why 'application.name' and 'application.user_id'are not working when more than one records receive.
Here is my query using yii2
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search_vendor_certificates($user_id)
{
$query = ApplicationCertificates::find()->joinWith('application b',true , 'INNER JOIN')->where(["b.user_id"=>$user_id]);
// add conditions that should always apply here
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => $query,
]);
return $dataProvider; }
I will appreciate if someone would tell me what is the mistake I am doing in displaying the proper attributes of the application model.
First of all (don't use this, i'll show u an logical mistake):
->joinWith('application b',true , 'INNER JOIN')
U set alias for application b, and then in GridView use application. Anyway, it's still bad if u rename it to b in GridView.
Based on this answer:
Model TableTwo:
public function getTableOneRecord()
{
return $this->hasOne(TableOne::className(), ['id' => 't1_id']);
}
public function getTableThreeRecord()
{
return $this->hasOne(TableThree::className(), ['id' => 't3_id']);
}
public function getTableFourRecord()
{
return $this->hasOne(TableFour::className(), ['id' => 't4_id'])
->via('tableThreeRecord');
}
And the view file:
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
't1_id',
'tableOneRecord.id',
't3_id',
'tableThreeRecord.id',
'tableThreeRecord.t4_id',
'tableFourRecord.id',
],
]);
In easiest way to say, your relation from search won't work in GridView, you have to define relations in Model and then use thems ;)
See the code on GitHub

Same value for all columns fields yii2

I have gridview with some columns. I want to create one colums like
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['header' => 'Manager',
//'value' => 'first'],
Column name is Manager and all fields equels 'first'? How could I do this?
Based on info provided, this is easy to achieve with custom grid column:
<?php
namespace app\components;
class CommonValueColumn extends Column
{
public $commonValue = 'Default value for common value';
protected function renderDataCellContent($model, $key, $index)
{
return $commonValue;
}
}
Then use it in GridView widget like this:
'columns' => [
// ...
[
'class' => 'app\components\CommonValueColumn',
'header' => 'Manager',
'commonValue' => 'First',
],
// ...
],
Note that if the manager is a model attribute and the value needs to be taken from database, this is a wrong way to do it.
Information about GridView widget is available in the official docs.

merge on column based relational table in gridview yii2

in index.php :
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'ID_REQUEST',
'NOMOR_SURAT',
[
'label' => 'Nama Depan',
'attribute' => 'ID_KARYAWAN',
'value' => 'iDKARYAWAN.FIRST_NAME'
],
[
'label' => 'Nama Belakang',
'attribute' => 'ID_KARYAWAN',
'value' => 'iDKARYAWAN.LAST_NAME'
],
which is iDKARYAWAN is relation from another table in my model
class Request extends \yii\db\ActiveRecord {
/**
* #inheritdoc
*/
public static function tableName() {
return 'ytms_it.request';
}
public function getIDKARYAWAN() {
return $this->hasOne(Karyawan::className(), ['ID_KARYAWAN' => 'ID_KARYAWAN'])->from(Karyawan::tableName(). ' b');
}
How to merge those two column ?
For the elp, thanks.
Create method called getFullName() in related model and calculate full name using PHP concatenation:
use yii\helpers\Html;
...
/**
* #return string
*/
public function getFullName()
{
return Html::encode($this->name . ' ' . $this->surname);
}
Optionally define a label for it in attributeLabels() method of related model:
`fullName` => 'Label for full name',
Then in GridView it's possible to display full name of related model in one column like so:
1) The shortest form:
'relatedModel.fullName',
2) Overriding the label:
[
'attribute' => 'relatedModel.fullName',
'label' => 'Overrided label',
],
3) Using closure:
[
'attribute' => 'relatedModel.fullName', // The attribute name can be different in this case
'value' => function ($model) {
// You can calculate full name here.
// But it's better to just call according method since view is only for display.
return $model->author->fullName;
},
],
Another way is to calculate full name using SQL and include as a part of query result in separate column.
Use Active Record - Selecting extra fields official docs section as a guide, also see this related issue on Github - JoinWith - assign a column aliases to an attribute of related model.
Add $fullName as public property of related model class. Modify query like so:
use yii\db\Expression;
...
->joinWith(['relatedModel' => function (\yii\db\ActiveQuery $query) {
$query->addSelect('fullName' => new Expression("CONCAT(name, ' ', surname)")]);
}]
Then to display it in GridView column you can use one of the options desribed above, for example:
'relatedModel.fullName'

how to use function in DetailView yii2

**i use model function in detail view how i use function in detail view **
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'title',
'demand',
'sell_for',
'property_category',
'detail',
[
'attribute' => 'dealer_id',
'format'=>'raw',
'value'=> function ($model) {
return Dealer::getName($model->dealer_id);
}
],
],
]) ?>
**i use model function in detail view how i use function in detail view **
In DetailView value don't need anonymous function but only the assign ..
[
'attribute' => 'dealer_id',
'format'=>'raw',
'value'=> Dealer::getName($model->dealer_id);
],
see yii2 doc
return Dealer::getName($model->dealer_id)
Write out the code inside the getName function. If you want to get the name of the dealer using its id, then I think you should use the yii\db\ActiveQuery to sort that out. Lemme see your getName function

Yii2 how to anchor the value of the relationship in the GridView

I am beginner. I explain the topic:
there is this relationship in the Ticket model:
public function getTyp()
{
return $this->hasOne(Typology::className(), [ 'id' =>'typ_id']);
}
and in the ticket table there is the typ_id column (it is in relationship with the id of the Typology table).
In the view views/ticket/index.php there is GridView::widgetwith these columns:
[
'attribute' => 'typ_id',
'value' => 'typ.typology'
],
I want to anchor the value of the relationship.
I have tried this:
[
'attribute' => 'typ_id',
'value' => function ($model) {
return Html::a (
'typ.typology',
'/typology/view?id='.$model->typ_id
);
}
]
but it doesn't work
someone can help me?
Html::a() interprets typ.typology as raw string. Use $model in value closure to get necessary property through relation.
Also instead of manually concatenate the url with its parameters, just pass them in array (see Url::to() to understand how link is constructed).
[
'attribute' => 'typ_id',
'value' => function ($model) {
return Html::a($model->typ->typology, ['/typology/view', 'id' => $model->typ_id]);
},
],

Categories