I want to use pagination in my view, but I can't figure out how to do it in conjunction with the find() method.
Getting the numbers of pages works correctly, but it always displays all values from the database. I want to see 15 comments per page.
Here is my ViewAction controller:
public function actionView($id) {
$query = UrComment::find()->where(['IsDeleted' => 0]);
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>12]);
return $this->render('view', [
'model' => $this->findOneModel($id),
'comment' => UrComment::findComment($id),
'pagination'=> $pagination
]);
}
And this is how I get the comments:
public static function findComment($id)
{
if (($model = UrUser::findOne($id)) !== null) {
$Id=$model->Id;
$comment = UrComment::find()->where(['Rel_User' => $Id])->all();
return $comment;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
I tried to use this:
public function actionView($id) {
$query = UrComment::find()->where(['IsDeleted' => 0]);
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>12]);
$comment= UrComment::findComment($id);
$comment->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('view', [
'model' => $this->findOneModel($id),
'comment' =>$comment,
'pagination'=> $pagination
]);
}
But I get this error:
Call to a member function offset() on array
Then I display it in the view:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
$this->title = $model->Name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Użytkownicy'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ur-user-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Aktualizuj'), ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete', 'id' => $model->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
</p>
<?=
DetailView::widget([
'model' => $model,
'attributes' => [
'Id',
'Name',
'Surname',
'BirthDate',
'Login',
'Email:email',
['attribute' => 'Rel_Sex', 'value' => (isset($model->relSex->Name)? $model->relSex->Name : "Nie wybrano")],
['attribute' => 'Rel_Language', 'value' => (isset($model->relLanguage->Name)) ? $model->relLanguage->Name : "Nie wybrano"],
['attribute' => 'Rel_Country', 'value' => (isset($model->relCountry->Name)) ? $model->relCountry->Name : "Nie wybrano"],
['attribute' => 'Rel_Category', 'value' => (isset($model->relUserCategory->Name)) ? $model->relUserCategory->Name : "Nie wybrano"],
],
])
?>
Komentarze użytkownika: <?= $model->Name.' '.$model->Surname;?><br><br>
<?php foreach ($comment as $comm): ?>
<?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => $comm->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => $comm->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
<p><?= $comm->Text ?></p>
<hr>
<?php endforeach; ?>
<?php
echo \yii\widgets\LinkPager::widget([
'pagination' => $pagination,
]);
?>
</div>
</div>
</div>
How can I limit the UrComment::findComment($id) using the pagination?
EDIT:
I think I understand you, and I think I've done everything you told me in your answer, but now I have another problem. I need to display under view comments only that which is id view only this one person not all comments.
Here is what I have now:
ActionView:
public function actionView($id) {
$searchModel = new CommentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['IsDeleted' => 0]);
$dataProvider->pagination->pageSize=15;
return $this->render('view', [
'model' => $this->findOneModel($id),
'comment' => UrComment::findComment($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
CommentSearch:
<?php
namespace backend\modules\users\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\UrComment;
class CommentSearch extends UrComment
{
public function rules() {
return [
[['Id'], 'integer'],
[['Text'], 'safe'],
];
}
public function scenarios() {
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
public function search($params) {
$query = UrComment::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'Id' => $this->Id,
'Text' => $this->Text,
]);
$query->andFilterWhere(['like', 'Text', $this->Text]);
return $dataProvider;
}
}
View:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\widgets\ListView;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
$this->title = $model->Name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Użytkownicy'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ur-user-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Aktualizuj'), ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete', 'id' => $model->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
</p>
<?=
DetailView::widget([
'model' => $model,
'attributes' => [
'Id',
'Name',
'Surname',
'BirthDate',
'Login',
'Email:email',
['attribute' => 'Rel_Sex', 'value' => (isset($model->relSex->Name)? $model->relSex->Name : "Nie wybrano")],
['attribute' => 'Rel_Language', 'value' => (isset($model->relLanguage->Name)) ? $model->relLanguage->Name : "Nie wybrano"],
['attribute' => 'Rel_Country', 'value' => (isset($model->relCountry->Name)) ? $model->relCountry->Name : "Nie wybrano"],
['attribute' => 'Rel_Category', 'value' => (isset($model->relUserCategory->Name)) ? $model->relUserCategory->Name : "Nie wybrano"],
],
])
?>
Komentarze użytkownika: <?= $model->Name.' '.$model->Surname;?><br><br>
<?php
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => 'comments',
'viewParams' => ['comment' => $comment, 'model'=>$model],
]);
?>
</div>
</div>
</div>
And my item comments:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
?>
<?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => $comment->Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => $comment->Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
<p><?= $comment->Text ?></p>
<hr>
Using that code, now I have error that in this item in button edit:
$comment->Id], ['class' => 'btn btn-primary']) ?>
Trying to get property of non-object
And I can't use foreach there because I have duplicate comments. Should change something in comment Search or in my function findComment(id) inquiry?
There is my actual item 'comments' where I want to display text of comments and buttons to edit and delete comment. But this does not work for me. I have:
Use of undefined constant Id - assumed 'Id'
and
Use of undefined constant Text - assumed 'Text';
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model backend\modules\users\models\UrUser */
?>
<?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => Id], ['class' => 'btn btn-primary']) ?>
<?=
Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => Id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
'method' => 'post',
],
])
?>
<p><?= Text ?></p>
<hr>
If you use model and foreach in not easy, use pagination because pagination if base on dataProvider and not directly for model ..
Essentially finding the model like you did mean work direclty on the data while pagination don't work directly on the data but rather use the a sql query for retrive information from db a let these available to widgets .. this is what the dataProvider perform .. .. then I suggest you of use a widget like ListView and change your query based on a find with a dataProvider based on a modelSearch ..
public function actionView($id) {
$searchModel = new UrCommentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['IsDeleted' => 0]);
$dataProvider->pagination->pageSize=15;
return $this->render('view', [
'model' => $this->findOneModel($id),
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
and for view.php
<?php
echo ' <h1>User : ' . $model->userName . '</h1>';
echo '<h2>Comments</h2'>,
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_comment',
]);
where _comment is a partial view of you comment layout .,.
then in _comment.php you can simply
<?=$model->id;?>
<?=$model->text;?>
Related
under the course content there, I want to make the Active column to show either "Yes" or **"No"**At first it was showing "1" or "0", but that's not what I want to show. These are my attempted codes, and I'm getting this error. Appreciate it if anyone can please guide me.
Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: app\models\Coursecontent::isActive
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Course */
$this->title = $model->course_name;
$this->params['breadcrumbs'][] = ['label' => 'Courses', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
\yii\web\YiiAsset::register($this);
?>
<div class="course-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('<< Back', ['index'], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Update', ['update', 'id' => $model->course_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->course_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'course_name',
'description',
['attribute' => 'active', 'value' => $model->isActive,'contentOptions' => ['style' => $model->active == 1 ? 'color:green' :'color:red']],
'lastupdate',
],
]) ?>
<h2>Course Content</h2>
<?= Html::a('Create Coursecontent', ['coursecontent/create'], ['class' => 'btn btn-success']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'chapter_name',
'description',
'video_link',
['attribute' => 'active',
'value' => function ($model, $key, $index, $column) {return $model->isActive;},
'contentOptions' => function ($model, $key, $index, $column) {
return $model->active == 1 ? ['style' => 'color:green'] : ['style' => 'color:red'];
}],
['class' => 'yii\grid\ActionColumn',
'contentOptions' => ['class' => 'text-center'],
'buttons' => [
'view' => function ($url,$model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>',['coursecontent/view', 'id' => $model->coursecontent_id]);
},
'update' => function ($url,$model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',['coursecontent/update', 'id' => $model->coursecontent_id]);
},
'delete' => function ($url,$model) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>',['coursecontent/delete', 'id' => $model->coursecontent_id],
['data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]);
},
]],
],
]); ?>
</div>
Have to make 2 changes to your code.
Change all $model->isActive to $model->active.
Return "Yes" or "No" depending to $model->active value.
Update DetailView:
[
'attribute' => 'active',
'value' => function ($model) {
return $model->active ? "Yes" : "No";
},
'contentOptions' => ['style' => $model->active ? 'color:green' :'color:red']
],
Update GridView:
[
'attribute' => 'active',
'value' => function ($model) {
return $model->active ? "Yes" : "No";
},
'contentOptions' => function ($model, $key, $index, $column) {
return $model->active ? ['style' => 'color:green'] : ['style' => 'color:red'];
}
],
The model is Booking.php. I need to get data from another model called ServiceCategory.php and add a filter to it in Gridview on my index.php. I created filter on view/index.php as below.
['label' => 'Service Category', 'attribute' => 'category.name', 'filter' => ArrayHelper::map(app\models\Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
This is my index.php
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\grid\GridView;
use app\models\Servicecategory;
/* #var $this yii\web\View */
/* #var $searchModel app\models\BookingSerach */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Bookings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="list-booking">
<h1 class=""><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p class="form-inline text-right">
<label>Client:</label>
<?= Html::dropDownList('client', null, ArrayHelper::map($clients, 'id', 'fullname'), ['prompt' => 'Please Select', 'class' => 'form-control']) ?>
<?= Html::a('+ New Booking', ['booking/create/'], ['class' => 'btn btn-primary client-create']) ?>
</p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
['label' => 'Client', 'value' => 'user.client.view', 'format' => 'raw'],
'postCode',
'start',
'end',
['label' => 'Service Category', 'attribute' => 'category.name', 'filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
//'numberOfDays',
//'date',
//'followUpEmail:email',
// 'followUpEmailSent:ckeckbox',
//'Status',
['attribute' => 'status', 'value' => 'Status', 'filter' => array_filter(\app\models\Booking::$statuses)],
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp(this, "' . $url . '")', 'checked' => false, 'id' => 'followup'];
}
],
['class' => 'yii\grid\ActionColumn',
'headerOptions' => ['style' => 'width:15%'],
'template' => '{view} {approval} {update} {delete} ',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', ['/booking/review/' . $model->id], [
'title' => Yii::t('app', 'Review'),
]);
},
'approval' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-ok"></span>', ['/booking/approval/' . $model->id], [
'title' => Yii::t('app', 'Additional Details'),
'class' => 'error',
]);
},
],
],
],
]);
?>
</div>
<?php
$script = <<< JS
$('.client-create').on('click', function () {
select = $(this).prev();
if(select.val()){
location.href = $(this).attr('href')+"/"+select.val();
} else {
$(this).parent().addClass('has-error');
}
return false;
});
JS;
$this->registerJs($script);
$this->registerJs("
function followUp(e, url){
$('#modal').modal('show').find('#modalContent').load(url);
}", yii\web\View::POS_END);
?>
I can get the data to the column on gridview but the filter is not working. Can anyone help me with this?
I solved it myself. For your information I post it here. I changed the attribute as the model contains and added the value as category.name
['attribute' => 'categoryID', 'value' => 'category.name','filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
If I try to update records,I get following error without any ideas, what's about or what this error could have been caused by.
Furthermore, it's strange, that this error only will be bred by records having been imported by a dump. There will be no error, if I will update a record having been created using saveasnew option. Unfortunately, I can't delete this record in order to recreate it,'cause it would expel against referential integrity.
Here is error:
Invalid Configuration – yii\base\InvalidConfigException
Unable to locate message source for category 'mtrelt'.
throw new InvalidConfigException("Unable to locate message source for category '$category'.")
2. in ...\vendor\yiisoft\yii2\i18n\I18N.php at line 88 – yii\i18n\I18N::getMessageSource('mtrelt')
3. in ...\vendor\yiisoft\yii2\BaseYii.php at line 509 – yii\i18n\I18N::translate('mtrelt', 'Data can't be deleted because it...', [], 'de-DE')
4. in ...\vendor\mootensai\yii2-relation-trait\RelationTrait.php at line 312 – yii\BaseYii::t('mtrelt', 'Data can't be deleted because it...')
Here is model:
<?php
namespace common\modules\lookup\models\base;
use Yii;
use mootensai\behaviors\UUIDBehavior;
class LPersonArt extends \yii\db\ActiveRecord
{
use \mootensai\relation\RelationTrait;
public function relationNames()
{
return [
'eAppEinstellungArts',
'lKontaktVerwendungszwecks',
'people'
];
}
public function rules()
{
return [
[['person_art'], 'string', 'max' => 50],
[['zieltabelle'], 'string', 'max' => 100],
[['bemerkung'], 'string', 'max' => 255]
];
}
public static function tableName()
{
return 'l_person_art';
}
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'person_art' => Yii::t('app', 'Personengruppen'),
'zieltabelle' => Yii::t('app', 'Zieltabelle'),
'bemerkung' => Yii::t('app', 'Bemerkung'),
];
}
public function getEAppEinstellungArts()
{
return $this->hasMany(\common\modules\erweiterung\models\EAppEinstellungArt::className(), ['id_person_art' => 'id']);
}
public function getLKontaktVerwendungszwecks()
{
return $this->hasMany(\common\modules\lookup\models\LKontaktVerwendungszweck::className(), ['id_person_art' => 'id']);
}
public function getPeople()
{
return $this->hasMany(\common\modules\basis\models\Person::className(), ['id_person_art' => 'id']);
}
public function behaviors()
{
return [
'uuid' => [
'class' => UUIDBehavior::className(),
'column' => 'id',
],
];
}
public static function find()
{
return new \common\modules\lookup\models\LPersonArtQuery(get_called_class());
}
}
Here is Controller:
public function actionUpdate($id)
{
$model = new LPersonArt();
if (!Yii::$app->request->post('_asnew') == '1'){
$model = $this->findModel($id);
}
if ($model->load(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
Here is view:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="lperson-art-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model); ?>
<?= $form->field($model, 'id', ['template' => '{input}'])->textInput(['style' => 'display:none']); ?>
<?=
$form->field($model, 'person_art')->widget(\jlorente\remainingcharacters\RemainingCharacters::classname(), [
'type' => \jlorente\remainingcharacters\RemainingCharacters::INPUT_TEXTAREA,
'text' => Yii::t('app', '{n} characters remaining'),
'options' => [
'rows' => '3',
'class' => 'col-md-12',
'maxlength' => 50,
'placeholder' => Yii::t('app', 'Write something')
]
])
?>
<?=
$form->field($model, 'bemerkung')->widget(\jlorente\remainingcharacters\RemainingCharacters::classname(), [
'type' => \jlorente\remainingcharacters\RemainingCharacters::INPUT_TEXTAREA,
'text' => Yii::t('app', '{n} characters remaining'),
'options' => [
'rows' => '3',
'class' => 'col-md-12',
'maxlength' => 255,
'placeholder' => Yii::t('app', 'Write something')
]
])
?>
<div class="form-group">
<?php if (Yii::$app->controller->action->id != 'save-as-new'): ?>
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php endif; ?>
<?php if (Yii::$app->controller->action->id != 'create'): ?>
<?= Html::submitButton(Yii::t('app', 'Save As New'), ['class' => 'btn btn-info', 'value' => '1', 'name' => '_asnew']) ?>
<?php endif; ?>
<?= Html::a(Yii::t('app', 'Cancel'), Yii::$app->request->referrer, ['class' => 'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Problem will be solved adding following code into components of
common/config/main-local.php
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#backend/messages', // if advanced application, set #frontend/messages
'sourceLanguage' => 'de',
],
],
],
I was having a similar problem, but the Yii2 error message was
Unable to locate message source for category ''
I was running Gii from console:
php yii gii/crud --controllerClass="app\controllers\StcDocumentTypeController" --messageCategory="stc_document_type" --enableI18N=1 --enablePjax=1 --interactive=0 --modelClass="app\models\StcDocumentType" --searchModelClass="app\models\StcDocumentTypeSearch" --overwrite=1
The solution was to add the i18n configuration on the console.php config file:
'components' => [
...
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
'sourceLanguage' => 'en-US',
],
]
],
...
]
If you're running from web check also that config in web.php
I create filter form for my data using data provider and search model and have a problem, when my filter parameters copy in url when I click submit button more than one time.
Model's ApartmentsSearch search method:
public function search($params)
{
$query = Apartments::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'rooms' => $this->rooms,
]);
return $dataProvider;
}
Controller actionIndex method:
public function actionIndex()
{
$searchModel = new ApartmentsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->get());
return $this->render('index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
}
View with ListView widget:
<?= $this->render('_filter', ['searchModel' => $searchModel]); ?>
<?= ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_list',
'options' => [
'tag' => 'div',
'class' => 'apartments-list',
],
'layout' => '{summary}{items}{pager}',
'summary' => 'Показано квартири: <b>{begin}-{end}</b> з <b>{totalCount}</b>.',
'summaryOptions' => [
'tag' => 'div',
'class' => 'summary',
],
'itemOptions' => [
'tag' => 'div',
'class' => 'apartment-item',
],
]); ?>
And _filter.php view with form:
<?php $form = ActiveForm::begin([
'method' => 'get',
]); ?>
<?= $form->field($searchModel, 'rooms') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
So, when I input any number in field and click submit I see url like this:
http://localhost/?ApartmentsSearch[rooms]=2
When I click second time I see url with copied parameter:
http://localhost/?ApartmentsSearch[rooms]=2&ApartmentsSearch[rooms]=2
I don't want copy parameters in url, I need to change value of any parameter.
Can you help me?
Solved.
In active form I forgot add action property:
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($searchModel, 'rooms') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
I want to show images instead of image name in admin panel. but i got many examples in yii 1.1 but not understanding to use in yii 2.0.
here is my grid view
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\imagine\Image;
/* #var $this yii\web\View */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Contents');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="content-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Create Content'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'label',
'title',
'content',
/* ['attribute' => 'main_image',
'header' => 'Image',
'value' => function( $data ) {
return ?><img src="<?= Yii::$app->request->baseUrl ?>/upload/content/<?php echo $data->main_image?>">
<?php
}
],*/
[
'attribute'=>'photo',
'value' => Html::a(Html::img(Yii::getAlias('#web').'/upload/content'.$content->main_image, ['alt'=>'some', 'class'=>'thing', 'height'=>'100px', 'width'=>'100px']), ['site/zoom']),
'format' => ['raw'],
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
I am getting error of undefined content,and I also tried the above code which are in comment. but it show 'not set' in filed list.
if any idea about that pls help...
You should format your attribute this way (hoping the path are correct)
['attribute' => 'main_image',
'header' => 'Image',
'format' => 'raw',
'value' => function( $model ) {
return '<img src="' . echo Yii::$app->request->baseUrl . '/upload/content/'. $model->main_image .'">' ;
}
],
I get the solution using this code
['attribute' => 'main_image',
'header' => 'Image',
'format' => ['raw'],
'value' => function( $data ) {
return Html::img(Yii::getAlias('#web').'/upload/content/'.$data->main_image, ['alt'=>'some', 'class'=>'thing', 'height'=>'100px', 'width'=>'100px']);
}
],