Giter VIP home page Giter VIP logo

yii-dataview's Introduction

Yii

Yii Data Displaying Extension


Latest Stable Version Total Downloads Build status Code Coverage Mutation testing badge

This package provides data displaying widgets:

  • ListView
  • GridView
  • DetailView

Requirements

  • PHP 8.1 or higher.

Installation

The package could be installed with Composer:

composer require yiisoft/yii-dataview

Documentation

If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.

License

The Yii Data Displaying Extension is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

yii-dataview's People

Contributors

aphraoh avatar dependabot-preview[bot] avatar dependabot[bot] avatar devanych avatar fantom409 avatar g-rodigy avatar gerych1984 avatar githubjeka avatar luizcmarin avatar mister-42 avatar particleflux avatar roxblnfk avatar rustamwin avatar samdark avatar sankaest avatar stylecibot avatar terabytesoftw avatar took avatar viktorprogger avatar vjik avatar xepozz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii-dataview's Issues

Should ListView/GridView return to first page when sort changes

I have noticed that I can be on page 3 of ListView but when I change the sort it remains on page 3. Logically you would expect it to return to page 1 since page 3 of a new sort is not very useful to the end user.

Should it be changed to go from page 1 when sort changes?

In OffsetPagination, no way of setting private member variables $labelPrevious, $labelNext, $labelFirst, $labelLast

What steps will reproduce the problem?

In OffsetPagination no way of setting private member variables below...
private string|Stringable|null $labelPrevious = '⟨';
private string|Stringable|null $labelNext = '⟩';
private string|Stringable|null $labelFirst = '⟪';
private string|Stringable|null $labelLast = '⟫';

What is the expected result?

Would expect public member functions below...
public function labelPrevious(string|Stringable|null $labelPrevious): self {$new=clone $this;$new->labelPrevious=$labelPrevious;return $new;}
public function labelNext (string|Stringable|null $labelNext): self {$new=clone $this;$new->labelNext=$labelNext; return $new;}
public function labelFirst (string|Stringable|null $labelFirst): self {$new=clone $this;$new->labelFirst=$labelFirst; return $new;}
public function labelLast (string|Stringable|null $labelLast): self {$new=clone $this;$new->labelLast=$labelLast; return $new;}

You can then do something like this...
$pagination = (new OffsetPagination())
->paginator($paginator)
->labelPrevious(NoEncode::string('<i class="fas fa-play fa-rotate-180"></i>'))
->labelNext(NoEncode::string('<i class="fas fa-play"></i>'))
->labelFirst(null)
->labelLast(null);

What do you get instead?

Instead you are stuck with the default setting.

Additional info

@vjik if you find this code change exceptable, I can do change and submit pull request.

Q A
Version master
PHP version 8
Operating system Window/Linux

Customizable/extendable column format parsing

This is a feature request.

Right now we can use "attribute:format:label" to describe the display rule of a column in GridView and DetailView, format declared the formatter to use. Developers can create their own custom formatter class by extending \yii\i18n\Formatter to add custom formatters to fit their needs. Sometimes developers may need to add some extra argument to a formatter to get more flexible control, then we'll need to create an array with a 'format' key instead to pass arguments to the formatter:

// for example:
// from
	'testAttr:example:Test Attr',
// to
	[
		'attribute' => 'testAttr',
		'label' => 'Test Attr',
		'format' = ['example', false],
	]

As a possible solution, I think using something like attribute:format(arg1,arg2):label to define the column display format could be handy, so as long as the arguments are not complex, developers won't need to stop and do the manual convert, so developers could keep focus on what they need to implement. I did a sample implementation to parse such format:

Example format string:
  • 'testAttr:example:Test Attr'
  • 'testAttr:example(true):Test Attr'
  • 'testAttr:example(true,false,"string",114514):Test Attr'

Sample implementation for Yii2 GridView

DataColumnTrait.php

<?php

namespace backend\traits;

use yii;
use yii\helpers\Html;
use yii\base\InvalidConfigException;
use yii\grid\DataColumn;

trait DataColumnTrait
{
/**
     * Creates a [[DataColumn]] object based on a string in the format of "attribute:format:label".
     * @param string $text the column specification string
     * @return DataColumn the column instance
     * @throws InvalidConfigException if the column specification is invalid
     */
    protected function createDataColumn($text)
    {
        if (!preg_match('/^([^:]+)(:(\w*)(\([\w,+_"]*\))?)?(:(.*))?$/', $text, $matches)) {
            throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
        }

        $formatArr = [
            isset($matches[3]) ? $matches[3] : 'text'
        ];

        if (isset($matches[4])) {
            $args = array_filter(explode(',', substr(trim($matches[4]), 1, -1)));
            foreach ($args as $arg) {
                // if (empty($arg)) continue;
                $arg = trim($arg);
                if ($arg[0] == '"') {
                    $actualVal = str_replace('"', '', $arg[0]);
                    array_push($formatArr, $actualVal);
                } elseif (is_numeric($arg)) {
                    array_push($formatArr, intval($arg));
                } elseif (in_array($arg, ["false", "true"])) {
                    array_push($formatArr, $arg == "true");
                } else {
                    throw new InvalidConfigException('Unrecognized argument(s), supported argument type are: true, false, digits(number) and double-quoteed string. Use comma to split multiple arguments');
                }
            }
        }

        return Yii::createObject([
            'class' => $this->dataColumnClass ?: DataColumn::class,
            'grid' => $this,
            'attribute' => $matches[1],
            'format' => $formatArr,
            'label' => isset($matches[6]) ? $matches[6] : null,
        ]);
    }
}

GridView.php

<?php

namespace backend\components;

use backend\traits\DataColumnTrait;

class GridView extends \yii\grid\GridView
{
    use DataColumnTrait;
}

But by looking into the implementation from the Yii codebase, it seems the logic of parsing that format string is live in different places and not as extendable as using a custom formatter, so I suggest we could make such thing extendable by extracting that part of logic and allow developer use their own "ColumnFactory" (example name) or make these *View use the same trait to do the column format parse job.

GridView - can't set css class on tbody when empty rows

Render GridView widget with empty rows and table bootstrap class table table-hover

tbody (which contains $emptyText) changes it's background color on hover but I can't control that, because class empty is assigned to the div inside tbody

emptyTextOptions should be assigned to the tbody instead of div inside it

empty

Q A
Yii version 2.0.?
PHP version 7.0
Operating system Windows

Dependabot can't resolve your PHP dependency files

Dependabot can't resolve your PHP dependency files.

As a result, Dependabot couldn't update your dependencies.

The error Dependabot encountered was:

Your requirements could not be resolved to an installable set of packages.
  Problem 1
    - Installation request for yiisoft/yii-web ^3.0@dev -> satisfiable by yiisoft/yii-web[3.0.x-dev].
    - yiisoft/yii-web 3.0.x-dev requires psr/http-factory-implementation 1.0 -> no matching package found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.
 - It's a private package and you forgot to add a custom repository to find it

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

If you think the above is an error on Dependabot's side please don't hesitate to get in touch - we'll do whatever we can to fix it.

View the update logs.

ListView summary tag not used if custom summary is supplied

Could be related to #2460

If you define a custom summary for list view the containing wrapper tag (default is div) is not rendered, making summaryOptions useless. We can add our div to the summary option like this as a workaround

'summary' => '<div class="summary">Showing ...'

But I don't think that's what's intended is it?

GridView columns shortcut declarations: allow value function as value

It would be nice if the columns could be defined this way:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel'  => $searchModel,
    'columns'      => [
        // ---- current style ----
        [
            'attribute' => 'full_name',
            'label'     => 'Name',
            'format'    => 'html',
            'value'     => function (Order $model) {
                return Html::tag('span', $model->first_name . '<br>' . $model->last_name);
            },
        ],
        // ---- new alternative style ----
        'full_name:html:Name' => function(Order $model) {
            return Html::tag('span', $model->first_name . '<br>' . $model->last_name);
        },
        ...
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

Would that be possible? Because of formatting I need to declare columns explicitly quite often. This would reduce the lines of code a bit.

ActionColumn.php grid yii 2.1 with BS4.

Yii Version; 2.1.
Bootstrap: 4.1.
PHP Version: 7.1.17.
Operating System: Centos 7.

Hi, ActionColumn.php support icons glyphicons, Bootstrap 4.1.0 no support glyphicons, it should be rewritten so that the user indicates the icons to use, or use independent icons of BS3 and BS4 for default.

Code Glyphicons:

    /**
     * Initializes the default button rendering callbacks.
     */
    protected function initDefaultButtons()
    {
        $this->initDefaultButton('view', 'eye-open');
        $this->initDefaultButton('update', 'pencil');
        $this->initDefaultButton('delete', 'trash', [
            'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
            'data-method' => 'post',
        ]);
    }
    /**
     * Initializes the default button rendering callback for single button.
     * @param string $name Button name as it's written in template
     * @param string $iconName The part of Bootstrap glyphicon class that makes it unique
     * @param array $additionalOptions Array of additional options
     * @since 2.0.11
     */
    protected function initDefaultButton($name, $iconName, $additionalOptions = [])
    {
        if (!isset($this->buttons[$name]) && strpos($this->template, '{' . $name . '}') !== false) {
            $this->buttons[$name] = function ($url, $model, $key) use ($name, $iconName, $additionalOptions) {
                switch ($name) {
                    case 'view':
                        $title = Yii::t('yii', 'View');
                        break;
                    case 'update':
                        $title = Yii::t('yii', 'Update');
                        break;
                    case 'delete':
                        $title = Yii::t('yii', 'Delete');
                        break;
                    default:
                        $title = ucfirst($name);
                }
                $options = array_merge([
                    'title' => $title,
                    'aria-label' => $title,
                ], $additionalOptions, $this->buttonOptions);
                $icon = Html::tag('span', '', ['class' => "glyphicon glyphicon-$iconName"]);
                return Html::a($icon, $url, $options);
            };
        }
    }

GridView causes 500 error

I think it is about configuration. When I add GridView on page, I got 500 Internal Server Error.

What steps will reproduce the problem?

php composer.phar require yiisoft/yii-dataview

vendor/yiisoft/yii-base-web/src/controllers/SiteController.php

public function actionAbout()
{
    $array = [
        ['id' => 1, 'file' => '1.txt', 'name' => '1'],
        ['id' => 2, 'file' => '2.txt', 'name' => '2'],
    ];

    $dataProvider = new \yii\data\ArrayDataProvider([
        'allModels' => $array,
        'pagination' => [
            'pageSize' => 10,
        ],
    ]);

    return $this->render('about', ['provider' => $dataProvider]);
}

vendor/yiisoft/yii-base-web/src/views/site/about.php

...
<?=
\yii\dataview\GridView::widget([
    'dataProvider' => $provider,
    'columns' => [
        'id',
        'name',
        'file',
    ],
]);
?>

What is the expected result?

GridView with the data

What do you get instead?

An internal server error occurred.

Additional info

vendor/yiisoft/yii-core/src/data/BaseDataProvider::__construct($id = null) gets config array as $id. As result, any statement like $this->id . '-page'; throws error Array to string conversion. I changed input config:

$dataProvider = new \yii\data\ArrayDataProvider([
    'key' => 'id',
    'allModels' => $array,
    'pagination' => [
        'pageSize' => 10,
    ],
]);

and replace all $this->id . to $this->id['key'] .. After that the error is gone but table renders without any content in it (only header).

I do something wrong, but what exactly?

Q A
Yii version 3.0
PHP version 7.2.15
Operating system Ubuntu

Suggestion: Html::clearButton() for search and filter forms

In 8608 someone else has already thought that Html::resetButton() would work differently. I just stumbled over this too and I wondered if it would be possible to introduce something like Html::clearButton(). Although I know that it is the standard behaviour, the reset button of a form is quite useless, and it would be very helpful if there would be a way to clear a form and possibly submit it with the same click.

I think it is a very common requirement for search/filter inputs. And it would be also nice if gii could generate forms with such buttons. Could be also introduced for GridView filter inputs.

Currently, I do the following which seems to work:

<?= Html::resetButton('Reset', [
    'class'   => 'btn btn-default',  
    'onclick' => "$(this).closest('form').find('input, select, textarea').val(''); " .
                 "$(this).closest('form').submit(); " . 
                 "return false;"
]) ?>

Not perfect - it requires that the select has an empty option.

What do you think?

ListView and semantics

In an attempt to write semantical correct HTML I used a ListView with:

'options' => [ 'tag' => 'ol' ], 'itemOptions' => [ 'tag' => 'li' ]

However, I learned that the summary and the pager appeared inside the OL, like a kind of list items, which they are certainly not.

Of course, there are ways to work around this, such as overriding renderItems(), but it occurs to me that there must be a simpler way to get a semantical correct list out of ListView.

Perhaps something to consider for Yii3?

[Proposal] GridView::headOptions

I propose to add a property yii\grid\GridView::headOptions. This will allow us to use this bootstrap4 opportunities.

What steps will reproduce the problem?

<?= yii\grid\GridView::widget([
    'dataProvider' => new yii\data\ArrayDataProvider([
        'allModels' => [
            ['col1' => 'val1-1', 'col2' => 'val1-2'],
            ['col1' => 'val2-1', 'col2' => 'val2-2'],
        ],
    ]),
    'headOptions' => ['class' => 'thead-light'],
]); ?>

What is the expected result?

<table>
    <thead class="thead-light">
        ...
    </thead>
    ...
</table>

What do you get instead?

Error: Setting unknown property yii\grid\GridView::headOptions

Additional info

Q A
Yii version 2.0.15.1
PHP version 7.1.27
Operating system Ubuntu

Class 'yii\widgets\Widget' not found

I was trying to get this installed in my yii-demo, but it failed when initiating the object as it's not able to find class yii\widgets\Widget.
Did i miss something or are there dependency errors.

What steps will reproduce the problem?

Install yiisoft/yii-demo with composer create project
Require yiisoft/yii-dataview

What is the expected result?

Able to use widgets provided in this package.

What do you get instead?

Got an error message Class 'yii\widgets\Widget' not found when trying to initiate the widget.

Additional info

Q A
Version dev
PHP version 7.3.6
Operating system Windows 10

Query limit not working with pager enabled.

The pagerination pageSize overrides the limit set in the query

$query = Objects::find()->orderBy('name ASC')->limit(50);
        $dataProvider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => array('pageSize' =>24)
        ]);

The above produces

find.count({"ns":"geekobjects.objects","limit":-1,"batchSize":0,"skip":-1,"flags":0,"query":{},"fields":[],"started_iterating":false})

Which in turns overrides the limit of 50 and returns all of the collections instead of 50

$query = Objects::find()->orderBy('name ASC')->limit(50);
        $dataProvider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => false
        ]);

the above produces

find({"ns":"geekobjects.objects","limit":50,"batchSize":0,"skip":0,"flags":0,"query":{"$query":{},"$orderby":{"name":1}},"fields":[],"started_iterating":false})

which limits the query to 50 items but now there isn't a pager since it was set to false.

I don't know if it was intended to do this / or if this is a bug / or if I'm not doing this correctly.

Any proposed way of setting or disabling pageSizeLimit

yii2 REST API uses ActiveDataProvider to fetch and show data. This class has pageSizeLimit parameter which by default limit our pageSize to 50, so no matter how high is per-page (pageSizeParam) query parameter, maximum 50 rows are returned.

Is there any way to completely disable pageSizeLimit so that provider will show as many rows as we want by specifying per-page query parameter or defaultPageSize if not specified? Setting pageSizeLimit to false forces to always return defaultPageSize rows no matter what we pass by per-page.

Further investigation of source code showed, that setting pageSizeLimit to anything but false or two-dimensional array works, because the code in that case completely ignores pageSizeLimit link.

Won't it be better if we have framework proposed way of doing it and not hack, e.g. specifying only lower limit, or setting it true or something to obviously take the query param? I can make pull request if we come up with the way of specifying it...

Multiple overkill calls attributeLabels() and t() from GridView

What steps will reproduce the problem?

In case GridView $model->attributeLabels() called on each column (count of call = count of column n) on default. Also label can be generated each time.

i.e. each time call chain:
renderHeaderCellContent() -> getHeaderCellLabel()
->
$model->getAttributeLabel($this->attribute) -> $this->attributeLabels() -> $this->generateAttributeLabel($attribute) -> Inflector::camel2words($name, true) -> standart fn : strtolower trim str_replace preg_replace ucwords

Also if i18n enabled calling Yii::t() on each translated model feild m (count of call = n*m)

What is this mean?
Ordinary model have static labels. Also between creation of the first and last column the array of labels not changed (time to render view, logic of changing model is end in the previous time)

Information about model labels can be store outside $searchModel or GridView
directly in view (gii change)

$this->params['breadcrumbs'][] = $this->title;
$attributeLabels = $searchModel->attributeLabels
?>
...
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            [
                'attribute' => 'seq',
                'label' => $attributeLabels['seq'],

or into GridView model with autofill attribute (may be closure?)

Additional info

Q A
Yii version dev
PHP version 7.2
Operating system alpine

ActionColumn buttons (by default) reset filters

What steps will reproduce the problem?

  1. Create GridView with ActionColumn and filters/sorting features.
  2. Select some filters and sort some columns
  3. Click button in ActionColumn
  4. As result - all filters reseted

What is the expected result?

Filters/Sorters should be saved/restored after clicking buttons in action column.

What do you get instead?

All filters reseted, after clicking actionColumn button.

As temporary solution, it's possible use closure in action column

[
'class' => '\yii\grid\ActionColumn',
'urlCreator' => function ($action, $model, $key, $index) {

 $request = \Yii::$app->getRequest();
 $paramsFromRequest = $request instanceof \yii\web\Request ? $request->getQueryParams() : [];

$params = is_array($key) ? $key : ['id' => (string) $key];
$params[0] = \Yii::$app->controller->id . '/' . $action;

return \Yii::$app->urlManager->createUrl(array_merge($paramsFromRequest, $params));
]

Additional info

Method createUrl() also used in Pagination.php, Sort.php, but in these classes for creating Url is used current parameters from request, so we don't have problems with resetting filters/sorting.

But for action column we should use slightly different solution because, creteUrl will be executed for each row/column, so we need params 'caching' (may be in GridView widget) from request for avoiding $paramsFromRequest = $request instanceof \yii\web\Request ? $request->getQueryParams() : []; calculating in each row.

Q A
Yii version 2.0.7-372-g5921865
PHP version PHP 5.6.11
Operating system Ubuntu

Suggestion: Filter class for GridView / or DatePicker filter

All my tables contain a time stamp using the TimestampBehavior which i find very useful, but when i make the grids its a pain because filtering by date is not supported b default so i use the yii\jui\DatePicker class on the filter like this

GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        [
            'attribute' => 'created_at',
            'format' => ['date', 'php:Y-m-d'],
            'filter' => DatePicker::widget([
                // write model again
                'model' => $searchModel,
                // write attribute again
                'attriute' => 'created_at',
                // write format again
                'format' => ['date', 'php:Y-m-d'],
            ),
            // this is meaningless
            'filterInputOptions' => ['anything you put here gets ignored']
        ],
    ],
])

I propose to create a yii\grid\BaseFilter class which we can extend and create new functionalities. Currently the current classes would be InputFilter and DropdownFilter

The changes on the code would be editing the line https://github.com/yiisoft/yii2/blob/master/framework/grid/DataColumn.php#L166 to check if there is a 'class' index, and if so use that value to create a Yii Objecct. Otherwise use DropdownFilter class for arrays, InputFilterfor booleans and a simple return for strings.

Another option would be creating a DatePickerColumn class on the yii2-jui extension but that would make yii2-jui dependant on yii2-grid

Undefined property: App\Invoice\Entity\Inv Cycle ORM Proxy::$id

What steps will reproduce the problem? Testing

What is the expected result? Smooth run

What do you get instead? Error

Additional info

Q A
Version 1.0.?
PHP version 8.2
Operating system Windows 11

..resources/view/invoice/inv/index.php

<?php
    $read_with_iterable_type = $paginator_with_readabledatainterface_type->read();
    /**
     * @var ColumnInterface[] $columns
     */
    $columns = [
          new DataColumn(
              'id'
          )   
    ];
?>
<?php  echo GridView::widget()
    // unpack the contents within the array using the three dot splat operator    
    ->columns(...$columns)
    ->dataReader($paginator_with_readabledatainterface_type)    
?>

Hi Vijk,
If I pass an empty array for $columns, the GridView attempts to build the ActionColumns ie. view etc and I get the following error as well:

image

I thought this might be of interest. The code appears not to be accepting the DataColumn's first argument id because it has no property type associated with it ie. undefined property. This appears to be a Cycle issue.

Sort::link() - three states toggle

Sort Widget supports only two toggle states: first is default sorting, second is opposite to default sorting. It's unable to reset sorting by some field using Sort::link().

Link should have three states: default sort ->opposite sort -> no sort -> default sort -> opposite sort -> no sort ... etc., including the multisort.

Unable to display 0 (zero) as an attribute value in Detail View

What steps will reproduce the problem?

echo DetailView::widget()
    ->model([])
    ->attributes([
        [
            'label' => 'Zero Value',
            'value' => static function() { return '0'; }
        ],
        [
            'label' => 'Non-zero Value',
            'value' => static function() { return '1'; }
        ],
        [
            'label' => 'Bigger Value',
            'value' => static function() { return '99'; }
        ],
        [
            'label' => 'Negative Value',
            'value' => static function() { return '-1'; }
        ]
    ])
    ->render();

What is the expected result?

<table id="w1-detailview" class="table table-striped table-bordered detail-view">
<tbody>
<tr><th>Zero Value</th><td>0</td></tr>
<tr><th>Non-zero Value</th><td>1</td></tr>
<tr><th>Bigger Value</th><td>99</td></tr>
<tr><th>Negative Value</th><td>-1</td></tr>
</tbody>
</table>

What do you get instead?

<table id="w1-detailview" class="table table-striped table-bordered detail-view">
<tbody>
<tr><th>Zero Value</th><td></td></tr>
<tr><th>Non-zero Value</th><td>1</td></tr>
<tr><th>Bigger Value</th><td>99</td></tr>
<tr><th>Negative Value</th><td>-1</td></tr>
</tbody>
</table>

Additional info

Issue is caused by the if clause at line 142 in Yiisoft\Yii\DataView\DataAttribute.php

        if (empty($value)) {
            return '';
        }

because

empty('0') === true

hence an empty string is returned instead of '0'

LinkPager loose main css class before is defined

What steps will reproduce the problem?

Create a LinkPager widget and set only the "options" key with an empty array as value.
echo LinkPager::widget([ 'pagination' => $pages, 'options'=>[ ] ]);

What is the expected result?

Should keep "pagination" css class.

What do you get instead?

It looses its css class.

Additional info

Q A
Yii version 2.0.10
PHP version 5.5.3
Operating system OSX

Pagination: page attribute, wrong count.

I want to keep page for pagination in GridView. So I use Yii::$app->session.
But the page for the pagination component is not the actual saved page value but, instead, that value minus one. Why?

What steps will reproduce the problem?

function search ()
    {
        if ($data = Yii::$app->request->get()) Yii::$app->session['cita_params'] = $data;
        $params = Yii::$app->session['cita_params'];
        $query = self::v_cita();
        $dataProvider = new ActiveDataProvider([
        		'query' => $query,
        		'pagination' => [
        		    'pageSize' => 30,
        		    'page' => $params['page'] - 1
        		],
        ]);

What is the expected result?

I should be able to use just the saved page number.

What do you get instead?

Additional info

Q A
Yii version 2.0.12
PHP version 5.6
Operating system Linux Mint Debian edition

Suggestion: PageSize changer in LinkPager widget

I think it will be usefull to make options/methods in LinkPager for generating div with pageSize change links:
Show 10 | 25 | 50 | 100 records on page
Where 10, 25, 50, 100 - links to ?page=3&per-page=X (also current pageSize value can be plain text without link). This values can be set in Pagination options and can override pageSizeLimit option (to allow user choose only this values instead of pageSizeLimit range).

GridView empty column options

The current available options for GridView empty column are $emptyCell, $emptyText, and $emptyTextOptions.
Is there any configuration like $emptyColumnOptions or similar function ?

From yii\grid\Gridview source line 489:
return "<tbody>\n<tr><td colspan=\"$colspan\">" . $this->renderEmpty() . "</td></tr>\n</tbody>";

Q A
Yii version 2.0.12

GridView, can you help to provide freeze pane function?

Dear Yii2 Team,

Some grid widget can provide freeze top header function. However, I do not find any Yii2 grid can help to freeze left columns function.

Do you have a plan to enable GridView to provide function to freeze first several columns when scroll to right, just like excel freeze pane? thanks.

Regards,
Scott Huang

Doesn't translate messages

I think in di.php incorrect 'tags'(need 'translation.categorySource'?)

Additional info

Q A
Version 3
PHP version 8.2

Missing encode(false) in GridView::renderColumnGroup

When i using GridView options like this
[ 'class' => ***, 'options()' => [ [ 'style' => [ 'width' => '200px' ] ] ] ]

it render that encoded output

&lt;col style="width: 200px;"&gt;   | &lt;col style="width: 200px;"&gt;   | &lt;col style="width: auto;"&gt;

To fix it need add encode(false) to colgroup render in renderColumnGroup method

Dynamic style and css class Yiisoft\Yii\DataView\GridView

Add the ability to include style and add class when rendering td in Yiisoft\Yii\DataView\GridView

GridView::widget()
    ->columns(
        new DataColumn(property: 'id', header: 'ID', contentOptions: function ($model, $key, $index, $column) {
    // Динамически определяем классы и стили в зависимости от значения статуса
    $class = '';
    $style = '';

    if ($model->status == 'active') {
        $class = 'active-status';
        $style = 'color: green;';
    } elseif ($model->status == 'inactive') {
        $class = 'inactive-status';
        $style = 'color: red;';
    }

    return ['class' => $class, 'style' => $style];
    ),
        new DataColumn(property: 'matchCount', header: 'Матчей'),
        new DataColumn(property: 'win', header: 'Побед'),
        new DataColumn(property: 'kda', header: 'КДА'),
    )

contentOptions example from yii2

config ActiveDataProvider db

What steps will reproduce the problem?

Config ActiveDataProvider db

Error Mesage

Argument 1 passed to yii\activerecord\data\ActiveDataProvider::__construct() must implement interface yii\db\ConnectionInterface

Additional info

How to configure the connection of the db with ActiveDataProvider.

Q A
Yii version 3.0
PHP version 7.2.14
Operating system Centos 7

Using 'rowOptions' result in a crash

What steps will reproduce the problem?

$dp = new \yii\data\ArrayDataProvider();
$dp->allModels = [
    ['id' => 1, 'name' => 'Item 1'],
    ['id' => 2, 'name' => 'Item 2'],
];

echo \yii\dataview\GridView::widget([
    'dataProvider' => $dp,
    'rowOptions' => function ($model) {
        return ['class' => 'foo-' . $model['id']];

    },
]);

What is the expected result?

For the grid view to have additional classes on rows.

What do you get instead?

Error: Cannot use object of type yii\di\Container as array in /Users/didou/yii3/myapp/src/views/site/index.php:25

Additional info

Printing the backtrace, I think that there's something wrong going on with the dependency injection during the widget initialization:

#0  yii\view\View->{closure}()
#1  call_user_func() called at [/Users/didou/yii3/myapp/vendor/yiisoft/di/src/AbstractContainer.php:464]
#2  yii\di\AbstractContainer->resolveDependencies() called at [/Users/didou/yii3/myapp/vendor/yiisoft/di/src/AbstractContainer.php:357]
#3  yii\di\AbstractContainer->buildFromConfig() called at [/Users/didou/yii3/myapp/vendor/yiisoft/di/src/AbstractContainer.php:163]
#4  yii\di\AbstractContainer->buildWithoutDefinition() called at [/Users/didou/yii3/myapp/vendor/yiisoft/di/src/AbstractContainer.php:132]
#5  yii\di\AbstractContainer->build() called at [/Users/didou/yii3/myapp/vendor/yiisoft/di/src/AbstractContainer.php:158]
#6  yii\di\AbstractContainer->buildWithoutDefinition() called at [/Users/didou/yii3/myapp/vendor/yiisoft/di/src/AbstractContainer.php:132]
#7  yii\di\AbstractContainer->build() called at [/Users/didou/yii3/myapp/vendor/yiisoft/di/src/Factory.php:48]
#8  yii\di\Factory->create() called at [/Users/didou/yii3/myapp/vendor/yiisoft/yii-core/src/helpers/BaseYii.php:69]
#9  yii\helpers\BaseYii::createObject() called at [/Users/didou/yii3/myapp/vendor/yiisoft/view/src/widgets/Widget.php:132]
#10 yii\widgets\Widget::widget() called at [/Users/didou/yii3/myapp/src/views/site/index.php:31]
#11 require(/Users/didou/yii3/myapp/src/views/site/index.php) called at [/Users/didou/yii3/myapp/vendor/yiisoft/view/src/view/View.php:363]

the provided callback, wrongly identified as a dependency, ends up being called from AbstractContainer line 464

Q A
Yii version 3.0
PHP version 7.1.19
Operating system macOS Darwin Kernel Version 18.2.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.