Search code examples
phpsymfonysymfony-console

How to format the first column in a Symfony Table the same as the first row?


A Symfony Table normally colors the first row differently from the other rows. I would however like to have the first row AND the first column to have the same styling. I know there exists a TableStyle but I can not figure out how to give the first column + first row the same styling. In this example Table I would like the first column to also color green (the text Row A, Row B and Row C).

This example Table can be generated using the following code:

$table = new Table($output);
$table
    ->setHeaders(array('Col A', 'Col B', 'Col C'))
    ->setRows(array(
        array('Row A', 'Divine Comedy', 'Dante Alighieri'),
        array('Row B', 'A Tale of Two Cities', 'Charles Dickens'),
        array('Row C', 'The Lord of the Rings', 'J. R. R. Tolkien'),
    ))
;
$table->render();

examplee

Cheers


Solution

  • You need to create TableStyle instance and set cellRowContentFormat like this:

    <?php
    
    use Symfony\Component\Console\Helper\Table;
    
    require_once 'vendor/autoload.php';
    
    $output = new Symfony\Component\Console\Output\ConsoleOutput();
    $table = new Table($output);
    $style = new \Symfony\Component\Console\Helper\TableStyle();
    $style->setCellRowContentFormat('<info> %s </info>');
    $table->setColumnStyle(0, $style);
    $table
        ->setHeaders(array('Col A', 'Col B', 'Col C'))
        ->setRows(array(
            array('Row A', 'Divine Comedy', 'Dante Alighieri'),
            array('Row B', 'A Tale of Two Cities', 'Charles Dickens'),
            array('Row C', 'The Lord of the Rings', 'J. R. R. Tolkien'),
        ))
    ;
    $table->render();
    

    You can take a look on TableStyle::$cellRowContentFormat and TableStyle::$cellHeaderFormat members default values: by default $cellHeaderFormat is '<info>%s</info>', and this value makes cell header green (info color).