How to do a breakline in yii2?

Viewed 37

I'm trying to combine two data into one column. I already managed to combine two data in one column. But my problem is I don't know how to do a break line to separate the data. I have tried this way but doesn't work.

This is my code

'NAME_PROG_ENG'.'REMARKS' => ['label' => "Programme Name",'value' => function ($data) {return ($data->NAME_PROG_ENG)."\r\n".nl2br("Previously known as: ".($data->REMARKS));}],
1 Answers

I think you refer to GridView component.

Some explanation:

'NAME_PROG_ENG'.'REMARKS' =>

the array index is the model field name, you can't combine 2 columns just by concatenating the column name. In this way you just define a column in the grid wich is not connected to the model. This is not an error, is just to notice that this does not give you the expected result.

'value' => function ($data) {return ($data->NAME_PROG_ENG)."\r\n".nl2br("Previously known as: ".($data->REMARKS));}

Between $data->NAME_PROG_ENG and $data->REMARKS you put a "\r\n" which is fine, but you apply nl2br() function only to the second part of the string.

Now about Gridview. Text are automatically converted to entities, this is a security feature to avoid script injection from user input. If you plan to use input from an untrusted user, ensure that you clean it using htmlpurifier before saving it in database or before showing it (in your 'value'=>... function)

https://www.yiiframework.com/search?language=en&version=2.0&type=guide&q=htmlpurifier

You can bypass html entity conversion by specifies the output format as raw in grid column option

'format'=>'raw'

So you column definition should be something like

'prog_and_remark_combined' => [
    'format' => 'raw',
    'label' => "Programme Name",
    'value' => function ($data) {
        return nl2br(
            $data->NAME_PROG_ENG .
            "\r\nPreviously known as: " .
            $data->REMARKS
        );
    }
],

Gridview allow a short notation

https://www.yiiframework.com/doc/api/2.0/yii-grid-gridview#$columns-detail

which is like this

<column name>:<fomat>:<label>

your code can be as follow as well

'prog_and_remark_combined:raw:Programme Name' => [
    'value' => function ($data) {
        return nl2br(
            $data->NAME_PROG_ENG .
            "\r\nPreviously known as: " .
            $data->REMARKS
        );
    }
],

Last note, if the fields does not contain new line to be converted, just concatenate them without using nltobr() function

return $data->NAME_PROG_ENG . "<br>Previously known as: " . $data->REMARKS
Related