New in Symfony 4.2: Console tables improvements

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Using tables to display tabular contents in console commands are one of the most popular features of the Console component. In Symfony 4.2 we improved them with new features to display titles and set their maximum column width.
Adding titles to tables
Contributed by
Dany Maillard
in #26933.
In Symfony 4.2 tables can now display a title both at the top and the bottom of
its contents with the setHeaderTitle()
and setFooterTitle()
methods,
which is ideal for complex or paginated tables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
use Symfony\Component\Console\Helper\Table;
// ...
$table = new Table($output);
$table
->setHeaderTitle('Books')
->setFooterTitle('Page 1/2')
->setHeaders(['ISBN', 'Title', 'Author'])
->setRows([
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'],
// ...
])
;
$table->render();
This is how the above example would look in your terminal:
1 2 3 4 5 6 7 8
+---------------+----------- Books --------+------------------+
| ISBN | Title | Author |
+---------------+--------------------------+------------------+
| 99921-58-10-7 | Divine Comedy | Dante Alighieri |
| 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
| 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
| 80-902734-1-6 | And Then There Were None | Agatha Christie |
+---------------+--------- Page 1/2 -------+------------------+
Setting the max width of columns
Contributed by
Roland Franssen
in #28373.
The width defined with the setColumnWidth()
method is considered the minimum
column width. If the contents don't fit, the column width is increased up to the
longest content length. In Symfony 4.2 we added a new setColumnMaxWidth()
method to wrap long contents into multiple lines to maintain the column width.
1 2 3 4 5 6 7
// ...
// the first argument is the column position (starting from 0) and
// the second argument is the max length in characters
$table->setColumnMaxWidth(0, 5);
$table->setColumnMaxWidth(1, 10);
$table->render();
This example sets the max length of the first column to 5 characters and the max length of the second column to 10 characters. The give contents no longer fit into those columns, so they wrap into multiple lines:
1 2 3 4 5 6 7 8
+-------+------------+--------------------------------+
| ISBN | Title | Author |
+-------+------------+--------------------------------+
| 99921 | Divine Com | Dante Alighieri |
| -58-1 | edy | |
| 0-7 | | |
| (the rest of rows...) |
+-------+------------+--------------------------------+
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments





Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.