gii generated models successfully (with relations) :
/**
* #return \yii\db\ActiveQuery
*/
public function getClient()
{
return $this->hasOne(Client::className(), ['id' => 'client_id']);
}
but when i generated crud, in client filed just input text field.
Help me please, where is problem?
That's correct. In your _form.php file you have to define a dropdown box if the user should choose a client:
<?= $form->field($model, 'client')->dropDownList($clients) ?>
and in controller actions create/update you have to provide the $clients:
return $this->render('create', [ // or: return $this->render('update', [
'model' => $model,
'clients' => ArrayHelper::map(Client::find()->all(), 'id', 'name'),
]);
Don't forget to pass them in the view files for create.php and update.php to the _form.php file:
<?= $this->render('_form', [
'model' => $model,
'clients' => $clients, // <-- added
]) ?>
In other views where you just want to show client you may use this:
echo $model->client->name; //or something different
Related
I have problems with loading data from database.
My goal is to implement a MVC which dynamically shows in the view the values stored in the db table. So, in the Project model I have this code:
public function search($params)
{
$query = project::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'position' => $this->position,
'created_at' => $this->created_at,
'is_deleted' => $this->is_deleted,
]);
$query->andFilterWhere(['ilike', 'title', $this->title])
->andFilterWhere(['ilike', 'description', $this->description])
->andFilterWhere(['ilike', 'link', $this->link])
->andFilterWhere(['ilike', 'image', $this->image]);
return $dataProvider;
}
In the Controller:
public function actionIndex()
{
$searchModel = new SeachProject();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
And in the view (index.php):
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'title',
'description',
'image',
],
]); ?>
Well, it works but I need to print the values into Uikit cards and not through Gridview limitations (which is actually the only way I know). I should have one card for each record in the table with an image (the url in the image field of the table) and a link (the url in the link field of the table).
Any words of advise would be good, thanks in advance!
You can use ListView and create any kind of structure using UiKit cards or material design.
The ListView widget is used to display data from a data provider. Each
data model is rendered using the specified view file. Since it
provides features such as pagination, sorting and filtering out of the
box, it is handy both to display information to end user and to create
data managing UI.
A typical usage is as follows:
use yii\widgets\ListView;
use yii\data\ActiveDataProvider;
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_ui-card',
'viewParams' => [
'fullView' => true,
'context' => 'main-page',
],
]);
The _ui-card view file could contain the following basic card html :
<?php
use yii\helpers\Html;
use yii\helpers\HtmlPurifier;
?>
<div class="uk-card">
<div class="uk-card-header">
<h3 class="uk-card-title"><?= Html::encode ( $model->title ) ?></h3>
</div>
<div class="uk-card-body"><img src="<?= Html::encode ( $model->image ) ?>"><?= Html::encode ( $model->link ) ?></div>
<div class="uk-card-footer"></div>
</div>
This way you can show every project as a separate card using the view file.
Hope this helps
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
]
I'm using wbraganca dynamic forms. I have these codes in my controller :
public function actionView($id)
{
$rackObjects = RackObjects::find()->where(['rackID' => $id])->one();
if (!$rackObjects) {
throw new NotFoundHttpException('Empty rack');
}
return $this->render('view', [
'model' => $this->findModel($id),
'rackObjects' => $rackObjects,
]);
}
my view file :
<div class="col-lg-6">
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'rackID',
'height',
'width',
],
]) ?>
</div>
<div class="col-lg-6">
<h3>Objects in <?= $this->title ?></h3>
<?= DetailView::widget([
'model' => $rackObjects,
'attributes' => [
'ObjectTitle',
'objectID',
'rack_unit',
'Attached'
],
]) ?>
</div>
I want to have all my rackObjects in multiple detailview not only one detailview like this example : http://wbraganca.com/yii2extensions/dynamicform-demo1/view?id=721
how should I write the codes like example? There is no codes in demos!
$rackObjects = RackObjects::find()->where(['rackID' => $id])->all();
probably as u have already tried all(),
i'd suggest a try in your view file along with querying all()
foreach ($rackObjects as $rackObject) {
<?= DetailView::widget([
'model' => $rackObject,
'attributes' => [
'ObjectTitle',
'objectID',
'rack_unit',
'Attached'
],
]) ?>
}
what it does is, when you have queried all, you get an array of objects and you might want to loop your widget over each of the objects. and gives you multiple detailViews as you desire.
hope this helps.
You are returnig only one row, as you specify
$rackObjects = RackObjects::find()->where(['rackID' => $id])->one();
Replace that with ->all();
Modify value of columns in you detail view if you want everything in one grid.
Amir zaghari.
I'm newbie in YII2 and I use wbraganca\dynamicform\DynamicFormWidget;
I try to follow your step to show data in Detailview but I got an error.
Undefined variable: id
maybe I made something wrong. so can you explain how to coding in
public function actionView($id)
in controller.php
and
DetailView::widget
to display data in _view.php
thank you, sir
I add another table field in my view , but the search button disappeared , How can I retrieve this form button ?
SaleItems = And a table mysql database.
<?php
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'formatter' => ['class' => 'yii\i18n\Formatter','nullDisplay' => ''],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
**[
'attribute' => 'Data',
'content' => function(SaleItems $model, $key, $index, $column) {
return date('d/m/Y', strtotime($model->sale->date));
},
'header' => 'DATA'
],**
]); ?>
</div>
The search field disappears because in not setted properly in searchModel ..
for this you must extend the related modelSeacrh adding the relation with the related model and the filter for the field you need ..
for this you must set in the base mode, the relation
public function getSale()
{
return $this->hasOne(Sale::className(), ['id' => 'sale_id']);
}
/* Getter for sale data */
public function getSaleData() {
return $this->sale->data;
}
then setting up the search model declaring
/* your calculated attribute */
public $date;
/* setup rules */
public function rules() {
return [
/* your other rules */
[['data'], 'safe']
];
}
and extending
public function search($params) {
adding proper sort, for data
$dataProvider->setSort([
'attributes' => [
.....
'data' => [
'asc' => ['tbl_sale.data' => SORT_ASC],
'desc' => ['tbl_sale.data' => SORT_DESC],
'label' => 'Data'
]
]
]);
proper relation
if (!($this->load($params) && $this->validate())) {
/**
* The following line will allow eager loading with country data
* to enable sorting by country on initial loading of the grid.
*/
$query->joinWith(['sale']);
return $dataProvider;
}
and proper filter condition
// filter by sale data
$query->joinWith(['sale' => function ($q) {
$q->where('sale.data = ' . $this->data . ' ');
}]);
Once you do al this the searchModel contain the information for filter and the search field is showed in gridview
What in this answer is just a list of suggestion
you can find detailed tutorial in this doc (see the scenario 2 and adapt to your need)
http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/
I'm working on Yii2 Advance Application. I've two tables user (default yii2 db schema table) and user_profile(newly added). I've created relation between them by adding user_profile_id in user table and also made change in their respective models.
Following code added in User Model:
/**
* #return \yii\db\ActiveQuery
*/
public function getUserProfile() {
return $this->hasOne(UserProfile::className(), ['id' => 'user_profile_id']);
}
And in UserProfile Model
/**
* #return \yii\db\ActiveQuery
*/
public function getUsers()
{
return $this->hasMany(User::className(), ['user_profile_id' => 'id']);
}
Now, when I'm trying to pull data of UserProfile model from User gridview its giving me error:
User Gridview:
<?=
GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
'userProfile.first_name',
[
'class' => 'yii\grid\ActionColumn',
'header' => 'Action',
'template' => ' {update} {delete}',
],
],
]);
?>
(see userProfile.first_name)
Error:
Unknown Class – yii\base\UnknownClassException
Unable to find 'backend\models\UserProfile' in file: D:\www\pcwf/backend/models/UserProfile.php. Namespace missing?
Where I'm going wrong. Any help would be appreciated.