Yii2 Custom Column Widths
I’ve get calls from businesses who try to do their own cloud data applications, but need a little help from time to time, such as customizing Yii2 column widths.
This time a client needed to customize the column widths in his grid views – a common task. But figuring out how to do it isn’t all that easy – even with Yii2’s online documentation and our good friend Google!
So let’s just do it!
Step #1 – Which Yii2 File to Edit?
Your query string will tell you which Yii2 file to edit –
If using “prettified” urls, the above would look like –
So, in your project folder list, look for “song” under “views” as in –
Using our example, the file you want to edit is “index.php”. Note that I made a copy saved as “index-2.php” before editing!
Which View File Line(s) to Edit?
In my case, the default view file (index.php under the view folder), listed my column names (id, song, bpm, etc..) with no modifiers, making many of the columns much wider than needed or desired.
Let’s say I want to change the width of my “bpm” column..
Finally, Change Column Width..
Wouldn’t it be nice if we could just change ‘bpm’, to ‘bpm’ => ‘width: 30px’? But then we wouldn’t need this article!
Nope. Instead, change ‘bpm’ entirely. In fact, delete it and replace the line with –
[ 'class' => 'yii\grid\DataColumn', 'attribute' => 'bpm', 'headerOptions' => ['class' => 'text-center'], 'label' => 'BPM', 'contentOptions' => ['style' => 'width: 30px;', 'class' => 'text-center'], ],
As you’ve probably figured out, you can change the alignment by changing the ‘text-‘ value to center, left or right. In this example, to left-justify would be –
[ 'class' => 'yii\grid\DataColumn', 'attribute' => 'bpm', 'headerOptions' => ['class' => 'text-left'], 'label' => 'BPM', 'contentOptions' => ['style' => 'width: 30px;', 'class' => 'text-left'], ],
..and don’t forget those nagging little commas after each ‘]’ That’s one reason why I love IDE’s like PhpStorm or NetBeans!
Remember – You’ve got a business to run, and time you spend working on cloud or web applications is time you’re not running your business. Consider putting your time to its best use and hiring me – your starving PHP coder – to handle this issues!
I do custom PHP, WordPress, Yii2, all web-related coding (HTML, CSS, JSON, Ajax, Curl, etc., etc.) and database work such as data conversions, reporting and yes – even data mining!
Give me a call and let’s talk about how I can help your business.