Yii2 : How to pass additional parameters to listview - php

I read this post and answer give by Songwut K. in this question:
Yii2 ListView and dataprovider
But i want to know that is possible to use second model in _item. Suppose the _item is a post in the forum that retrieves data from the $model but I'd like to use a different model like $comment for me comment on a this post and view the post together with a commentary as one _item. Imagie that item is post on facebook and it display only text, date and user which write this post. But how i can add comment to this from other model? I just want to pass my $comment to _item view.
I was tried add new Commnet in my controller:
public function actionIndex()
{
$model = new NewsForm();
$searchModel = new NewsSearch();
$comment= new UrComment();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->setSort(['defaultOrder' => ['Id'=>SORT_DESC]]);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->saveNews();
return $this->redirect(['/content/news']);
} else {
return $this->render('index', [
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'comment' => $comment
]);
}
}
And render this to index. But i can use my $comment only in index how can i pass this to _item? i tried this:
<?php
echo ListView::widget( [
'dataProvider' => $dataProvider,
'itemView' => '_item',
'summary'=>'',
'comment' => $comment
]); ?>
And tried in my _item:
<?= $model->getStatus($model->cnNewsContentType_Id); ?> <br>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($comment, 'Text')->textInput(['maxlength' => true])->label('Treść') ?>
<?php ActiveForm::end(); ?>
But have error:
Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: yii\widgets\ListView::comment
In _item i can only use $model. It is possible to pass my $comment to _item view? Pls help me

You should simply use viewParams :
Additional parameters to be passed to $itemView when it is being rendered. This property is used only when $itemView is a string representing a view name.
e.g. :
<?= ListView::widget( [
'dataProvider' => $dataProvider,
'itemView' => '_item',
'viewParams' => ['comment' => $comment],
'summary'=>'',
]); ?>

Related

Q: Yii2 load data from database

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

Yii2- Undefined variable: model

I tried my best to solve this , but I can't seem to figure out where the problem is. Here is my code:
In action controller
return $this->render('viewcreated', [
'dataProvider' => $dataProvider,
'model' => $this->findModel($id),
'id' => $model->id
/*'searchModel' => $searchModel*/
]);
View
$this->title = $model->id; // here it gives the error
How can I resolve it ?
Any help would be highly appreciated
remove line 'id' => $model->id , as you have not declared $model anywhere and using its value,so its giving error simple.
enter code here
You can do it as,
$model= $this->findModel($id);
return $this->render('viewcreated', [
'dataProvider' => $dataProvider,
'model' =>$model,
'id' => $model->id
]);
You must retrieve the value for $model outside the render call so the $model object is available for all the index you accessing in render call
$model= $this->findModel($id);
Once you have done all the attribute related to the $model object are available avoiding redeclaration so you can call render this way
return $this->render('viewcreated', [
'dataProvider' => $dataProvider,
'model' =>$model,
]);
the value $model->id in view should be accessible directly by the var $model passed on index 'model'

get values from table with foreign key

Hi I have 2 tables and models for them. First of them is
User
and second
News
I want to take user id from table News and draw her name and surname. There is printscreen of table News:
I am trying to use the function:
public function getUrUser()
{
$q= News::find()->where(['urUser_Id' =>'Id'])->one();
$RoyalUserData=User::findOne($q);
//$RoyalUserData= User::find()->where(['Id' => $q])->one();
return $RoyalUserData->Name;
}
But this doesnt work. Only when I prescribe to q value 3 for egzample then it work. I know that is the wrong code in my first line of my function probably. I know that is easy but I am a beginner and I've fought with the code for about 1 hour. Can anyone help me?
In my view I use this:
<?=$model->getUrUser();?>
And I use this in ListView.
My controller:
public function actionIndex()
{
$model = new NewsForm();
$searchModel = new NewsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->setSort(['defaultOrder' => ['Id'=>SORT_DESC]]);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->saveNews();
return $this->redirect(['/content/news']);
} else {
return $this->render('index', [
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
My index where i use _item:
echo ListView::widget( [
'dataProvider' => $dataProvider,
'itemView' => '_item',
], $options = ['class' => 'sorter'] ); ?>
And content of _item
<?php
use yii\helpers\Html;
?>
Treść Newsa:
<?=$model->Text;?> <br>
Autor:
<?=Yii::$app->user->identity->Name?>
<?=Yii::$app->user->identity->Surname?> <br>
Status Newsa:
<?=$model->cnNewsContentType_Id;?> <br>
<?= Html::a('Update', ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?><br><br><br>
The News::find()->where(['urUser_Id' =>'Id'])->one() return a model not a field
then you must get the id field by the model this way
public function getUrUser($id)
{
// you already have the news model so don't need retrieve it
// it's enough pass the urUser_Id by $id
$RoyalUserData=User::findOne($id);
return $RoyalUserData->Name;
}
Then if you want show the ($RoyalUserData) Name in _item
<?=$model->getUrUser($model->urUser_Id);?>
public function getUrUser()
{
$q = News::find()->where(['urUser_Id' =>'Id'])->one();
return $q->user->name;
}
In user model you should create relation:
class News extends ActiveRecord
{
// ...
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}

Yii 2.0 Getting data from model without widget

Can anyone give me sample of how to retrieve data from model without having to use Widget ? Because need to get data per table column and put them inside my own view (not using widget)
Controller :
public function actionIndex() {
$searchModel = new B2CProductsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
View :
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'sku',
'name',
'short_description',
'long_description',
'thumb_img:ntext',
'large_img:ntext',
'url_content:ntext',
'contact_info',
'status',
'currency',
'price',
'dimension',
'weight',
// 'created',
// 'modified',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
The widget above iterate through the element inside the predefined gridview,
but what I want to do instead is something like :
foreach($data as $ab) {
echo $ab->id;
}
You can do it this way:
/* assuming $data is an ActiveDataProvider object */
$models = $data->getModels();
foreach($models as $model) { ... }
see more here
If you are using an ActiveDataProvider:
Controller:
public function actionMyAction()
{
$dataProvider = new ActiveDataProvider([
'query' => MyModel::find(),
]);
return $this->render('my-results-page', [
'dataProvider' => $dataProvider,
]);
}
View:
<?php
foreach ($dataProvider->models as $model){
echo $model->myProperty;
}
?>
If you are using a query, such as this:
$query = (new \yii\db\Query())
->select('this, that')
->from('over_there');
$command = $query->createCommand();
$rows = $command->queryAll();
Then you can iterate over the result like this(assuming you passed it to the view in a variable called $dataProvider):
foreach($dataProvider as $data)
{
$data['myProperty'];
}

Yii2 ListView and dataprovider

What data must be sended to dataprovider?
In my controller:
public function actionIndex() {
$searchModel = new UserSearch();
$dataProvider = $searchModel->search( Yii::$app->request->queryParams );
//other stuff and sending array of params to view
in a view:
echo ListView::widget( [
'dataProvider' => $dataProvider,
] );
but i got only id`s:
And if i`m set single view like:
'itemView' => '_single',
how send data to _single.php ?
I mean - need default template for view list items like in GridView:
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'username',
'email:email',
'password',
'role',
//....
And then i got perfect grid:
Controller - SiteController.php
<?php
// Yii2 Listview Example : by Songwut Kanchanakosai, Thailand.
use common\models\Members;
use common\models\SearchMembers;
...
public function actionIndex() {
$searchModel = new SearchMembers();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
?>
View (1) - index.php
<?php
use yii\widgets\ListView;
...
echo ListView::widget( [
'dataProvider' => $dataProvider,
'itemView' => '_item',
] ); ?>
View (2) - _item.php
<?php
use yii\helpers\Html;
?>
<?=$model->name;?>
<?=$model->age;?>
<?=$model->mobile;?>
Example Result :
Songwut 36 +668-3949-5153
Prawee 41 +668-7323-2334
Kosol 32 +668-8014-0165
Utehn 39 +668-7874-5643
how send data to _single.php ?
Here is how, use $viewParams
$viewParams public property array $viewParams = []
Additional parameters to be passed to $itemView when it is being
rendered. This property is used only when $itemView is a string
representing a view name.
echo ListView::widget( [
'dataProvider' => $dataProvider,
'viewParams'=>['name'=>'My Name is Stefano'], //acccessed in view as $name with value 'My Name is Stefano'
] );
in official docs http://www.yiiframework.com/doc-2.0/yii-widgets-listview.html#$itemView-detail
$itemView public property
The name of the view for rendering each data item, or a callback (e.g. an anonymous function) for rendering
each data item. If it specifies a view name, the following variables
will be available in the view:
$model: mixed, the data model
$key: mixed, the key value associated with the data item
$index: integer, the zero-based index of the data item in the items array returned by $dataProvider.
$widget: ListView, this widget instance
So your User model data should be available in _single.php as $model->username
So i suppose can use Detail View in _single.php i think:
DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'username',
'email:email',
//....

Categories