Condition statement in value attr CGridView Yii

2.7k views Asked by At

when I do this in CgridView:

'value' => '$data->status == 1 ? "Payed" : "None" ',

it works, but when I do this:

'value' => 'if ($data->status == 1) { echo "Payed"; } else if($data->status == 2) { echo "Two"; } else { echo "None"; } '.

What I need to do to make work the second statement, or how I need to rewrite it?

4

There are 4 answers

0
Steve On BEST ANSWER

Convert your statement to use ternary if:

'value' => '$data->status == 1 ? "Payed": ($data->status == 2 ? "Two" : "None")',
1
nowiko On

my solution:

function checkStatus($status)
{
    if ($status == 1) {
        return "opl";
    } else if ($status == 2) {
        return "nal";
    } else {
        return "neopl";
    }
}

'value' => 'checkStatus($data->status)',

But your will work too) I will accept answer)

0
topher On

You could also use a function instead to give a bit more flexibility and make it more readable:

'value' => function($row, $data ) {
    if ($data->status == 1) { return "Payed"; } 
    else if($data->status == 2) { return "Two"; }
    else { return "None"; }
}
0
Delphine On

Just in case :

I've tried topher's solution and I found out that I had to switch param like that :

'value' => function($data, $row ) {
    if ($data->status == 1) { return "Payed"; } 
    else if($data->status == 2) { return "Two"; }
    else { return "None"; }
}

With topher's solution $data->attribute_name did not work and was, in fact, the row instead of the model..

Perhaps, if you don't need $row, don't pass it.