Mohan Prasad
Mohan Prasad

Reputation: 682

Calling the function once for two attributes in yii grid view

I have a common function where I use them for different purposes in my yii grid view. For instance say my attributes are col1 and col2. They both call the same function, based on the value I perform different actions. The function needs to go through millions of data before returning back to my grid view.

I am calling the function twice here once in col1 and once in col2. is there anyway that I can call the function only once and use it for both the attributes, which will be very handy? Any help regarding this will be great. Thank you.

array(
                'header'=>'Phrase Used',
                'htmlOptions'=>array('style'=>'width:10px;text-align:center;'),
                'value'=> function($data){
                            if($data->usedBankPhrase($data->bank_id) == 1) {echo "<span class=\"translated-badge\" title =\"Used \">u</span>";}
                            else{echo "<span class=\"badge\" style=\"background-color:red !important; padding:2px;\" title =\" Not Used \">nu</span>";}
                            },
                'filter'=>'',
            ),

    //delete button
    'remove' => array(
                        'visible'=>'!$data->usedBankPhrase($data->bank_id);',
                        'label' => 'Delete Phrase',
                        'imageUrl'=>  Yii::app()->request->baseUrl.'/images/icons/cross.png',
                        'options'=>array('class'=>'full-bank-delete', 'id'=>'\'remove-banker-\'.$data->bank_id'), //HTML options for the button tag.
                    ),

Upvotes: 0

Views: 156

Answers (1)

Yupik
Yupik

Reputation: 5031

In model:

Define property

public $storedUsedBankPhrase = null;

Create getter:

public function getCalculatedUsedBankPhrase() {
   if($this->storedUsedBankPhrase === null) {
      $this->storedUsedBankPhrase= $this->usedBankPhrase($this->bank_id);
   }
   return $this->storedUsedBankPhrase ;
}

In GridView use:

'value'=> function($data){
           if($data->calculatedUsedBankPhrase == 1) {...

Upvotes: 2

Related Questions