if-condition inside CGridView ?

hi,

how is it posssible to put a if condition inside a CGridView.

my problem is:

i get a 0 and 1 from my DB. (ex: $data->my_value)

now i want to display either yes or no inside a column (CGridView)

yes if it is 1 and no if 0.

how can i handle this?

thx in advance.

hi tofu2000,

my solution is to create a function to select the appropriate output

for the given value

eg.




function yes_or_no($val){

 return $val == 1 ? 'yes' : 'no';

}



then in your CGridView:





array(

 'name' => 'attribute_name',

 'value' => 'yes_or_no($val)',

),



Or more OOP…

Model which you use to CGridView:




	public function getYesNoText() {

		return $this->yesNoOptions[$this->my_value];

	}

	

	public function getYesNoOptions() {

		return array(

			0 => 'No',

			1 => 'Yes',

		);

	}



View with CGridView:




	array(

		'name'=>'my_value',

		'value'=>'$data->getYesNoText()',

	)



You can also specify the gridview column like this (doesn’t require a helper in your model):




array(

    'name'=>'My Value',

    'value'=>'$data->my_value ? \'Yes\':\'No\'',

    'type'=>'text',

),

this works great if you only have 2 value in the variable… but how do you make this statement work if there are more than 2? i have 4 values in a field (1,2,3,4) that i need to convert to text.

See r4nd4ll solution. It leads you to correct direction. Below is my example portion of code,

Since I used yiistrap, getFormattedStatusName() is specific to yiistrap. you can use getStatusOptions as filter in the CGridView and CActiveForm.

Model which you use to CGridView:




    const DRAFT = 0;

    const VERIFIED = 1;

    const FULFILLED = 2;

    const CANCELLED = 3;


    public function getStatusColors() {

        return array(

            self::DRAFT => TbHtml::LABEL_COLOR_DEFAULT,

            self::VERIFIED => TbHtml::LABEL_COLOR_SUCCESS,

            self::FULFILLED => TbHtml::LABEL_COLOR_INVERSE,

            self::CANCELLED => TbHtml::LABEL_COLOR_IMPORTANT,

        );

    }


    public function getStatusOptions() {

        return array(

            self::DRAFT => 'Draft',

            self::VERIFIED => 'Verified',

            self::FULFILLED => 'Fulfilled',

            self::CANCELLED => 'Cancelled',

        );

    }

        

    public function getStatusName() {

        $options = $this->getStatusOptions();


        return $options[$this->status];

    }


    // Formatted, but need yiistrap to work

    public function getFormattedStatusName() {

        $colors = $this->getStatusColors();


        return TbHtml::labelTb($this->getStatusName(), array('color' => $colors[$this->status]));

    }



View with CGridView:




...

array(

    'name'=>'status',

    'value'=>'$data->getFormattedStatusName()',

)

...