Answer the question
In order to leave comments, you need to log in
How to specify class for specific td in Yii2 GridView?
There was a task to add a class to a certain td in the tables
'columns' => [
[
'attribute' => 'user',
'format' => 'html',
'label' => Yii::t('articles.main', 'Автор'),
'value' => function ($model) {
return UserColumn::widget([
'userId' => $model->user_id
]);
}
],
[
'attribute' => 'text',
'format' => 'html',
'value' => function ($model) {
return '<div class="text-left">' . $model->text . '</div>';
}
],
...
...
<td> ... </td>
<td> ... </td>
...
'columns' => [
[
'attribute' => 'user',
'format' => 'html',
'options' => ['class'=>'test'],
'label' => Yii::t('articles.main', 'Автор'),
'value' => function ($model) {
return UserColumn::widget([
'userId' => $model->user_id
]);
}
],
Answer the question
In order to leave comments, you need to log in
/**
* @var array|\Closure the HTML attributes for the data cell tag. This can either be an array of
* attributes or an anonymous function that () that returns such an array.
* The signature of the function should be the following: `function ($model, $key, $index, $gridView)`.
* A function may be used to assign different attributes to different rows based on the data in that row.
*
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $contentOptions = [];
Many programmers will probably hate me now, but I'm tired of hearing that
GridView is bad and not flexible. Well, firstly, it inherits from other widgets, and if you are not too lazy, you can find several, and so, my code example is not ideal, only as one of the types of solution, so that you understand what can be squeezed out of it.
We write a function to the model News()
:
...
<?php
public function sklonen($n,$s1,$s2,$s3, $b = false){
$m = $n % 10; $j = $n % 100;
if($b) {$n = '<b>'.$n.'</b>';}
if($m==0 || $m>=5 || ($j>=10 && $j<=20)) {return $n.' '.$s3;}
if($m>=2 && $m<=4) {return $n.' '.$s2;}
return $n.' '.$s1;
}
...
...
public function actionNews()
{
$searchModel = new NewsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams); // ищешь через LIKE
return $this->render('news', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
...
NewsSearch()
:...
$dataProvider = new ActiveDataProvider([
'query' => News::find()->where(['visibility'=>1])->orderBy('date DESC'),
'pagination' => [
'pageSize' => 20, // говоришь системе мне нужно вывести 20 записей
],
]);
...
<?php
use yii\helpers\Html;
use yii\widgets\Pjax;
use yii\grid\GridView;
use budyaga_cust\users\models\News;
$this->title = 'Новости';
$this->params['breadcrumbs'][] = $this->title;
?>
<?php Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'showHeader' => false, // вырезаем шапку таблицы
'tableOptions' => [
'class' => 'table' // можно задать свой, тут 100% ширина блока
],
'options' => ['tag' => 'div', 'class' => 'col-lg-12'], // оборачиваем в div с Bootstrap CSS
'emptyTextOptions' => ['tag' => 'p', 'class' => 'text-center text-danger'],
'emptyText' => 'По вашему запросу ничего не найдено',
'summary' => '<br/><p class="text-center text-muted">Всего найдено '.News::sklonen( '{totalCount}', 'новость', 'новости', 'новостей').'</p>', // 127
'layout' => '{summary}{items}', // настраиваем внешний вид как нам надо
'columns' => [
//['class' => 'yii\grid\SerialColumn'], // нумерация строк может вообще не пригодится
[
// 'attribute' => 'img', // если много атрибутов в контенте можно это не писать
'format' => 'raw',
'label' => '',
'content'=>function($data){
return '
<div class="row">
<div class="col-md-3">
'.Html::a(Html::img('/img/box/'.$data->img,
[
'class' => 'thumbnail',
'alt' => $data->header,
'style' => 'width:100%;'
])
,'/new/'.$data->link).'
</div>
<div class="col-md-9 products">
'.Html::a($data->header, '/new/'.$data->link).'
'.Html::tag('p', $data->text).'
'.Html::a('подробнее', '#',['class' =>'buttons pull-right']).'
</div>
</div>
';
}
],
], // может понадобится по дизайну, чтобы пагинация была в другом месте
]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'showHeader' => false,
'showOnEmpty' => false,
'summary' => 'страницы {page} из {pageCount}',
'layout' => '<div class="page-nav td-pb-padding-side">{pager}<span class="pages">{summary}</span></div>', // формируем внешний вид пагинации
'pager' => [
'maxButtonCount' => 5, // максимум 5 кнопок
'options' => ['id' => 'mypager', 'class' => 'pagination'], // прикручиваем свой id чтобы создать собственный дизайн не касаясь основного.
'nextPageLabel' => '<i class="ionicons ion-arrow-right-c"></i>', // стрелочка в право
'prevPageLabel' => '<i class="ionicons ion-arrow-left-c"></i>', // стрелочка влево
],
]); ?>
<?php Pjax::end(); ?>
I'm not strong in yii2, but this is how it works
GridView::widget([
// ...
// --------------------- КЛАСС ДЛЯ строки -------------------------------
'rowOptions'=>function ($model, $key, $index, $grid){
$class=($model->confirmed)?'confirmed-row':'';
return [
'key'=>$key,
'index'=>$index,
'class'=>$class
];
},
'columns' => [
[
'attribute' => 'confirmed',
// ---------------------- КЛАСС ДЛЯ СТОЛБЦА -----------------------
'contentOptions' => ['class' => 'text-center'],
'value' => function ($model) {
// ...
},
'format' => 'html',
],
],
]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question