Parse $Data To Html Option In Cbuttoncolumn

Hi

I used override class of CButtonColumn

Code :


<?php

class XCButtonColumn extends CButtonColumn

{

	public $htmlOptions = array('class' => 'center vcenter');

	public $viewButtonOptions = array('class' => 'btn btn-default tip view');

	public $viewButtonImageUrl = '';

	public $viewButtonHtml;

	public $updateButtonOptions = array('class' => 'btn btn-default tip update');

	public $updateButtonImageUrl = '';

	public $updateButtonHtml;

	public $deleteButtonOptions = array('class' => 'btn btn-default tip delete');

	public $deleteButtonImageUrl = '';

	public $deleteButtonHtml;

	public $showImage = false;

	public $showHtml = true;




	protected function renderButton($id, $button, $row, $data)

	{

    	if (isset($button['visible']) && !$this->evaluateExpression($button['visible'], array('row' => $row, 'data' => $data))) return;

    	$label = isset($button['label']) ? $button['label'] : $id;

    	$url = isset($button['url']) ? $this->evaluateExpression($button['url'], array('data' => $data, 'row' => $row)) : '#';

    	$options = isset($button['options']) ? $button['options'] : array();

    	if (!isset($options['title'])) $options['title'] = $label;

    	if ($this->showImage) {

        	if (isset($button['imageUrl']) && is_string($button['imageUrl'])) {

            	echo CHtml::link(CHtml::image($button['imageUrl'], $label), $url, $options);

        	} else {

            	echo CHtml::link($label, $url, $options);

        	}

    	} else {

        	if (isset($button['html']) && is_string($button['html'])) {

            	echo CHtml::link($button['html'], $url, $options);

        	} else {

            	echo CHtml::link($button['html'], $url, $options);

        	}

    	}

	}


	protected function initDefaultButtons()

	{

    	if ($this->viewButtonLabel === null) $this->viewButtonLabel = Yii::t('zii', 'View');

    	if ($this->updateButtonLabel === null)

        	$this->updateButtonLabel = Yii::t('zii', 'Update');

    	if ($this->deleteButtonLabel === null)

        	$this->deleteButtonLabel = Yii::t('zii', 'Delete');

    	if ($this->viewButtonImageUrl === null)

        	$this->viewButtonImageUrl = $this->grid->baseScriptUrl .

            	'/view.png';

    	if ($this->updateButtonImageUrl === null)

        	$this->updateButtonImageUrl = $this->grid->baseScriptUrl

            	. '/update.png';

    	if ($this->deleteButtonImageUrl === null)

        	$this->deleteButtonImageUrl = $this->grid->baseScriptUrl

            	. '/delete.png';

    	if ($this->viewButtonHtml === null)

        	$this->viewButtonHtml = '<i class="icon-zoom-in iconwhite"></i>';

    	if ($this->updateButtonHtml === null)

        	$this->updateButtonHtml = '<i class="icon-edit iconwhite"></i>';

    	if ($this->deleteButtonHtml === null)

        	$this->deleteButtonHtml = '<i class="icon-trash iconwhite"></i>';

    	if ($this->deleteConfirmation === null)

        	$this->deleteConfirmation = Yii::t('zii', 'Are you sure you want to delete this item?');

    	$modelClass = $this->grid->dataProvider->modelClass;

    	$controller = strtolower($modelClass);

    	if (is_array(CActiveRecord::model($modelClass)->primaryKey))

        	$paramExpression = '",$data->primaryKey)';

    	else

        	$paramExpression = '",array("id"=>$data->primaryKey))';

    	foreach (array('view', 'update', 'delete') as $id) {

        	$button = array(

            	'label' => $this->{$id . 'ButtonLabel'},

            	'url' => 'Yii::app()->urlManager->createUrl("' . "$controller/$id$paramExpression",

            	'imageUrl' => $this->{$id . 'ButtonImageUrl'},

            	'html' => $this->{$id . 'ButtonHtml'},

            	'options' => $this->{$id . 'ButtonOptions'},

        	);

        	if (isset($this->buttons[$id]))

            	$this->buttons[$id] = array_merge($button, $this->buttons[$id]);

        	else

            	$this->buttons[$id] = $button;

    	}

    	if (!isset($this->buttons['delete']['click'])) {

        	if (is_string($this->deleteConfirmation))

            	$confirmation = "if(!confirm(" .

                	CJavaScript::encode($this->deleteConfirmation) . ")) return false;";

        	else

            	$confirmation = '';

        	if (Yii::app()->request->enableCsrfValidation) {

            	$csrfTokenName = Yii::app()->request->csrfTokenName;

            	$csrfToken = Yii::app()->request->csrfToken;

            	$csrf = "\n\t\tdata:{ '$csrfTokenName':'$csrfToken'

},";

        	} else

            	$csrf = '';

        	if ($this->afterDelete === null)

            	$this->afterDelete = 'function(){}';

        	$this->buttons['delete']['click'] = <<<EOD

function() {

$confirmation

var th = this,

afterDelete = $this->afterDelete;

jQuery('#{$this->grid->id}').yiiGridView('update', {

type: 'POST',

url: jQuery(this).attr('href'),$csrf

success: function(data) {

jQuery('#{$this->grid->id}').yiiGridView('update');

afterDelete(th, true, data);

},

error: function(XHR) {

return afterDelete(th, false, XHR);

}

});

return false;

}

EOD;

    	}

	}




}

But the problem I need to print $data variable in html option , and I know this not accept PHP expression ,so how to solve this ?

this code from gridview :


....

'translate2' => array(

                    	'label' => Yii::t('app', 'Translate'),

                    	'html' => '$data->news_id', // here my problem how to print this value 

                    	'options' => array('class' => 'btn btn-default tip '),

                    	'visible' => '$data->parent_id ==null and News::model()->checkDuplicateTranslate($data->news_id, News::model()->getButtonLanguage($data->news_id,1) )',

                    	'url' => 'Yii::app()->createUrl("news/createTranslation", array("news_id"=>$data->news_id,"lang"=>News::model()->getButtonLanguage($data->news_id,1)))',

                	),

....

Thanks in advance

It’s up to you, if you parse the $button[‘html’] option with ‘evaluateExpression’:

You code from renderButton above:





 protected function renderButton($id, $button, $row, $data)

        {

        if (isset($button['visible']) && !$this->evaluateExpression($button['visible'], array('row' => $row, 'data' => $data))) return;

     .....

        } else {

                if (isset($button['html']) && is_string($button['html'])) {

                //echo CHtml::link($button['html'], $url, $options); //<-----

//use evaluateExpression here instead, like 'visible' above 

echo $this->evaluateExpression($button['html'], array('row' => $row, 'data' => $data)))                


} else {

                echo CHtml::link($button['html'], $url, $options);

                }

        }

        }









Thank you Joblo , I tried it but I had this error:

[b]

[/b]

And what’s the code of your $button[‘html’]?

It starts with ‘<’ and is not a valid php expression like ‘$data->news_id’ as you told above or ‘CHtml::button(“test”)’ …

My bro Joblo , I called it direct like this :


'translate2' => array(

                    	'label' => Yii::t('app', 'Translate'),

                    	'html' =>'$data->news_id',

                    	'options' => array('class' => 'btn btn-default tip '),

                    	'visible' => '$data->parent_id ==null and News::model()->checkDuplicateTranslate($data->news_id, News::model()->getButtonLanguage($data->news_id,1) )',

                    	'url' => 'Yii::app()->createUrl("news/createTranslation", array("news_id"=>$data->news_id,"lang"=>News::model()->getButtonLanguage($data->news_id,1)))',

                	),

So how to call it ?

And where does the ‘<’ came from?

You should debug or var_dump in the method ‘renderButton()’.

See my comment at the guidlines.

This my full code , I had no idea what’s the error ?

http://www.yiiframework.com/forum/index.php/topic/56839-parse-data-to-html-option-in-cbuttoncolumn/page__view__findpost__p__258233

Please, please…

You have to take a look what’s coming in.

What is $botton[‘html’], what is $data, $data->attributes





protected function renderButton($id, $button, $row, $data)

        {

            if (isset($button['html'])

            {

               var_dump($id, $botton['html'], $row, $data, $data, $data->attributes);

               //die(); //maybe

            }


            .....

        }




:) OK thanks , but I guess it’s not useful to my status , I guess problem in this line


$this->evaluateExpression($button['html'], array('row' => $row, 'data' => $data)))//->

This var dump results :

Thanks for your help

On var_dump():

Please try only var_dump($botton[‘html’]);

The $botton[‘html’] must be a valid php expression to evaluate.

If not, you will get an error.

Hi Joblo ,

View :


'translate2' => array(

                    	'label' => Yii::t('app', 'Translate'),

                    	'html' =>'$data->news_id',

                    	'options' => array('class' => 'btn btn-default tip '),

                    	'visible' => '$data->parent_id ==null and News::model()->checkDuplicateTranslate($data->news_id, News::model()->getButtonLanguage($data->news_id,1) )',

                    	'url' => 'Yii::app()->createUrl("news/createTranslation", array("news_id"=>$data->news_id,"lang"=>News::model()->getButtonLanguage($data->news_id,1)))',

                	),

X:


....

if (isset($button['html']) && is_string($button['html'])) {

            	var_dump($button['html']);

            	die();

...



[b] Result:

[/b]

Your string has a length of 38, but seems to be empty "".

This might be strange, but is because var_dump doesn’t html encode.

Your data object with the method ‘news_id’ returns some html-code, but not a php expression.

It’s a string that starts with ‘<’ that cannot be evaluated.

Maybe you can check this by using var_dump(html_entities($button[‘html’])) or CVarDumper::dump($button[‘html’]);

Sorry I don’t what’s the value of $button[‘html’].

The best is, you install a debugger to check out the content of $button[‘html’] and why this is a string that starts with ‘<’.

Why don’t you use a debugger?

Thank for your time , I rated you by 5 stars in your profile :) to say thanks .

I guess the problem is not in running php code or not because php code worked perfect with out :


evaluateExpression()

also I called functions from model on it , the big problem when I call $data not worked and return this :

1- ‘$data->news_id’ will return string $data->news_id like our status

2- if i called it like that "$data->news_id" will return Undefined variable: data

I tried everything included (your solution ) , before I posted this question .

I have no idea what’s wrong or what is best way to call $data->news_id ?

However, thanks for your time :)

The problem is not evaluateExpression, the problem is, with which string you call this method.

If you set





'translate2' => array(

                        ...

                        'html' =>'$data->news_id',

                        ... 

                        ),



the incoming $button[‘html’] in renderButtons MUST be the string ‘$data->news_id’.




....

if (isset($button['html']) && is_string($button['html'])) {

                var_dump($button['html']); <------------------------ MUST be the string '$data->news_id'

                die();

...




If not, I can’t follow with your code snippets.

But believe me, install a debugger and you can solve the problem.

The last idea:

The invalid string for the evaluateExpression comes from another buttoncolumn, where you have assigned html-code to the ‘html’.

Seems that you have more buttons than the ‘translate2’ where you didn’t assign a string to evaluate.

I can’t see this in your submitted code.

If you have set


'html'=>'< ... some html ..>'

you have to change this to




'html'=>'return \'< ... some html ..>\'',



to ensure ‘html’ is a valid php expression string to evaluate.

[EDIT] and this buttoncolumn is ‘images’, as I can see at your full var_dump post from above.

Change this to ‘html’=> ‘return \’<img …\’’ or ‘echo CHtml::image(…)’ …

Or better name it ‘expression’ so it’s clear you have to assign a valid php expression string.

This should be the solution:

You can use ‘html’ for pure html, ‘link’ for links and ‘expression’ for terms where you need values from $data.

But the expression must always be a expression to evaluate




protected function renderButton($id, $button, $row, $data)

         ....

        } else {

                     

                if(isset($button['link'])) //output the link

                {

                    echo CHtml::link($button['link'], $url, $options);

                } 

                elseif(isset($button['html']))  //output the pure assigned html

                {

                    echo $button['html']; 

                } 

                elseif(isset($button['expression'])) //evaluate an expression

                {

                    echo $this->evaluateExpression($button['expression'], array('row' => $row, 'data' => $data)))

                } 

                

        }

        }




In you view:





'translate2' => array(

                        ...

                        'expression' =>'$data->news_id',

                        //or if you want to output html 

                        'expression' =>'CHtml::image($data->imageSrc)', 

                        ... 

                        ),




'images' => array(

                        ...

                        'link' =>'<img ....>', //output the image as link

                        ... 

                        ),


'pureimage' => array(

                        ...

                        'html' =>'<img ....>', //image without a link

                        ... 

                        ),






Thank you So much my bro Joblo , you fixed it :)