Sunday, 7 January 2018

Make Yii2 ListView play nice with UI frameworks

This is probably quite a common scenario: you are using a framework control, in my case a Yii 2 ListView, and trying to render a list of items that will form a coherent grid on the page.

The easiest way to get a grid is to use your UI grid - I am using Ink: and I like the fact that it is slightly more square than Bootstrap and looks imho more modern as a result.

Anyway, if you render a ListView by default (and I guess the same in other web frameworks) it tries to help by wrapping items in divs with a class and id, which obviously allows CSS flexibility but in my case, breaks the grid selectors from Ink, which are looking for direct descendants of the Ink grid (rightly or wrongly) and so it breaks.

In the case of the ListView, however, you can disable these divs by using options (for the whole list) and itemOptions (for each item). Of course, as well as removing them, you could customise them if that is what you want. What I ended up with is simply:

<?php echo ListView::widget([
    'dataProvider' => $dataProvider,
    'itemView' => '_lessongroup',
    'summary' => false,
    // The following are the two important lines for this example
    'itemOptions' => ['tag'=>false],
    'options' => ['tag'=>false]

It's always worth having a dig through the code of these framework controls, it is usually fairly easy to find out whether code is always rendered or whether there is some way to remove or override it.

Google might also be your friend!
Post a Comment