TV-customization (Part 8): Conditionally assigning CSS classes (2/2)

Now we know how to use an inline-SQL command case-when for dynamically evaluating and returning string values depending on database table values. It's time to put it all together.


Let's return to our PHP editor and clean up the code a bit. I have copied our case-when command of Part 7 and using it now for building our replacement string in PHP, see Lines 9-15.

function machines_init(&$options, $memberInfo, &$args)
    $options_old = $options->QueryFieldsTV;
    $options_new = [];

    foreach ($options_old as $sql => $column) {

        if ($column == 'year_of_manufacture') {
            $css_class = "(case
                year(now()) - year_of_manufacture
                when 0 then 'label label-success'
                when 1 then 'label label-warning'
                when 2 then 'label label-warning'
                else 'label label-danger'

            $parts = [
                "'<span class=\"'",
            $new_value = "concat(" . implode(", ", $parts) . ")";
            $options_new[$new_value] = $column;
        } else {
            $options_new[$sql] = $column;
    $options->QueryFieldsTV = $options_new;
    return true;

That's it, let's save and see the results:

And let's check the generated HTML of one of those elements:

Look good. You now have all required bricks for building your own customizations.

Teaser / Preview

If all of this is too complicated for you because you need to know several techniques (HTML, CSS, SQL, PHP), stay tuned, I consider publishing an easy-to-use PHP library. This library will make it much easier, have a short look, the code below produces exactly the same output with less code and is more readable:

// file: hooks/machines.php
function machines_init(&$options, $memberInfo, &$args)
    $table_highlighter = AppGiniHelperTVHighlighter::create("machines", $options);
    $column_highlighter = $table_highlighter->getColumnHighlighter("year_of_manufacture");
        ->if("year_of_manufacture <= year(now())-3")->then("label label-danger")
        ->if("year_of_manufacture <= year(now())-1")->then("label label-warning")
        ->else("label label-success");

    return true;

And that's the output of the Highlighter-code above:

If you are interested in such an easy-to-use library, please contact me so I will see if there is enough demand.

If you like the way I try to help you, please consider following me on Twitterpurchasing our products or donating a coffee. All of this will help me, helping you in the future.

Kind regards,

Do you like it?