Tlbexcelview-Related Discussion, Questions, And Issues

Hello erand,

In the view code, you need only the tlbExcelView widget, which extends the CGridView widget.

Now, for your question, do you mean you don’t want to show the data at all?

If my understanding is correct, there are two options I can think of:

[list=1]

[*]If you want to hide the tlbExcelView widget: I think it would be possible through CSS. But technically it must be there in the view.

[*]If you don’t want to load the view in the browser at all: the workflow in the sample code is not mandatory, you can as well force the export mode in the action, so that it only exports, and not display, the grid data.

[/list]

Hope it helps.

Hi bennouna,

Thank you for your reply.

If I leave only tlbExcelView widget it does not include serach functionality for each column right?

And I need that…(not the advanced search) So I need the CGridView…plus I am using ecolumns extension in CGridView…

Is hiding the tlbexcelview the only way?

Ok, so you can use the extended CGridView your way in the view.

When you want to export the filtered data:

  • you handle that through a button passing all the filter inputs to the controller action;

  • you call either another view with the tlbExcelView widget in export mode (so no HTML view display), or you keep a unique view, with a test on the [font=“Courier New”]$_GET[‘export’][/font] (or you pass an [font=“Courier New”]$export[/font] as a parameter to the view, and check it there).

I am not sure how to do that…It would be really nice but lets forget the filtered result (at least for now, maybe I try to figure it out later).

How can I do a full export (no filtering) but without showing the tlbexcel view?

Shall I make a different action with the same content as actionAdmin?

And a view for this action (containing the tlbexcelview), or?

Ok, please post both your controller (relevant action only) and view.

actionAdmin()


	public function actionAdmin()

	{

		if (isset($_GET['pageSize'])) {

			Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);

			unset($_GET['pageSize']);

		}

		$model=new Termin('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['Termin']))

			$model->attributes=$_GET['Termin'];


    	if (isset($_GET['export'])) {

        	$production = 'export';

    	} else {

        	$production = 'grid';

    	}

    	$this->render('admin', array('model' => $model, 'production' => $production));

	}

admin View:




<?php

/* @var $this TerminController */

/* @var $model Termin */


$this->menu=array(

	array('label'=>'List Termin', 'url'=>array('index')),

	array('label'=>'Create Termin', 'url'=>array('create')),

);


Yii::app()->clientScript->registerScript('search', "

$('#exportToExcel').click(function(){

    window.location = '". $this->createUrl('admin')  . $urlJoin . "' + $(this).parents('form').serialize() + '&export=true';

    return false;

    });

$('.search-button').click(function(){

	$('.search-form').toggle();

	return false;

});

$('.search-form form').submit(function(){

	$('#termin-grid').yiiGridView('update', {

		data: $(this).serialize()

	});

	return false;

});

");

?>




<?php 

$dialog = $this->widget('ext.ecolumns.EColumnsDialog', array(

		'options'=>array(

				'title' => 'Columns Order',

				'autoOpen' => false,

				'show' => 'fade',

				'hide' => 'fade',

		),

		'htmlOptions' => array('style' => 'display: none'), //disable flush of dialog content

		'ecolumns' => array(

				'gridId' => 'termin-grid', //id of related grid

				'storage' => 'db',  //where to store settings: 'db', 'session', 'cookie'

				//'fixedLeft' => array('CCheckBoxColumn'), //fix checkbox to the left side

				'fixedRight'=>array('CButtonColumn'),

				'model' => $model, //model is used to get attribute labels

				'columns'=>array(


					//////columns here

					

					array(

						'class'=>'CButtonColumn',

						/*'header'=>CHtml::dropDownList('pageSize', $pageSize, array(10=>10,20=>20,50=>50,100=>100),

						array(

							'onchange'=>"$.fn.yiiGridView.update('termin-grid',{ data:{pageSize: $(this).val() }})",

						)),*/

					),

				),

)));

$this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'termin-grid',

	'dataProvider' => $model->search(),

	'filter'=>$model,

	'columns' => $dialog->columns(),

	'template' => $dialog->link()."{summary}\n{items}\n{pager}",

)); ?>




        <?php echo CHtml::button(Yii::t('app', 'Export to Excel (xls)'), array('id' => 'exportToExcel')); ?>


and here I put the <?php $this->widget('application.components.widgets.tlbExcelView',....




So without changing your controller, you can make your view like this:


<?php

/* @var $this TerminController */

/* @var $model Termin */


if ($production == 'grid') {

    $this->menu=array(

        array('label'=>'List Termin', 'url'=>array('index')),

        array('label'=>'Create Termin', 'url'=>array('create')),

    );


...


    $this->widget('zii.widgets.grid.CGridView', array(

        'id'=>'termin-grid',

        'dataProvider' => $model->search(),

        'filter'=>$model,

        'columns' => $dialog->columns(),

        'template' => $dialog->link()."{summary}\n{items}\n{pager}",

    ));


    echo CHtml::button(Yii::t('app', 'Export to Excel (xls)'), array('id' => 'exportToExcel'));


} else {

    $this->widget('application.components.widgets.tlbExcelView', ...);

}



:) Perfect!

Just one last question:

If I don’t use the if else statement, in tlbexcelview:


'columns' => $dialog->columns()

works fine, like I have it in CGridView.

But when I use if else: Undefined variable: dialog

I have to put the whole array of columns so it can work with if else

Where is the problem?

Well the $dialog variable is defined in the first if part, so it’s not available in the else part.

A solution would be to declare the columns array outside the if test, and reference it in both parts…

Thank you very much for your help bennouna :)

Hi bennouna,

  1. How do I remove the footer (sumLabel)? I don’t want to show it at all…

  2. Is adding a header possible or not yet?

  3. Auto width is not working…columns are a bit bigger…how can I fix it?

Thank you in advance.

Hello erand,

[list=1]

[*][font="Courier New"]automaticSum[/font] property is your friend (set it to [font="Courier New"]false[/font])

[*]Not to my knowledge

[*]So I assume you’ve set [font=“Courier New”]autoWidth[/font] property to [font=“Courier New”]true[/font]. Maybe you can share the Excel file because on my side it always works…

[/list]

Cheers

Thank you for your reply.

About autoWidth, it works, but eg. the width of 2 columns are bigger than content (not so big, it’s not critical but I was just wondering if there is another attribute for fixing this).

Hi bennouna,

After I filter some data, exporting to excel gives all data (not only filtered ones)

I followed your suggestions about urlFormat but in both cases all data are exported…

Can you please help me?

Here is the code if needed:




<?php


$this->menu=array(

	array('label'=>'List Termin', 'url'=>array('index')),

	array('label'=>'Create Termin', 'url'=>array('create')),

);


$urlJoin = Yii::app()->urlManager->getUrlFormat() == 'path' ? '?' : '&';

Yii::app()->clientScript->registerScript('search', "

$('#exportToExcel').click(function(){

    window.location = '". $this->createUrl('admin')  .  "&' + $(this).parents('form').serialize() + '&export=true';

    return false;

    });

..........

");

?>


<h1>Manage Termine</h1>


<p>

You may optionally use these comparison operators for the search: <b>&lt;</b>, <b>&lt;=</b>, <b>&gt;</b>, <b>&gt;=</b>, <b>&lt;&gt;</b>

or <b>=</b>

</p>


<div class="search-form" style="display:block">

<?php $this->renderPartial('_search', array('model' => $model)); 

echo CHtml::button(Yii::t('app', 'Export to Excel (xls)'), array('id' => 'exportToExcel'));

?>

</div><!-- search-form -->


<?php 


$dialog = $this->widget('ext.ecolumns.EColumnsDialog', array(

		'options'=>array(

				'title' => 'Columns Order',

				'autoOpen' => false,

				'show' => 'fade',

				'hide' => 'fade',

		),

		'htmlOptions' => array('style' => 'display: none'), //disable flush of dialog content

		'ecolumns' => array(

				'gridId' => 'termin-grid', //id of related grid

				'storage' => 'cookie',  //where to store settings: 'db', 'session', 'cookie'

				//'fixedLeft' => array('CCheckBoxColumn'), //fix checkbox to the left side

				'fixedRight'=>array('CButtonColumn'),

				'model' => $model, //model is used to get attribute labels

				'columns'=>array(

					

                                        //all columns here


				),

)));


	$this->widget('application.components.widgets.tlbExcelView', array(

		'id'                   => 'termin-grid',

		'dataProvider'         => $model->search(array('condition'=>'t.lisDeleted=0')),

		'grid_mode'            => $production, // Same usage as EExcelView v0.33

		//'template'           => "{summary}\n{items}\n{exportbuttons}\n{pager}",

		...//all options here

		'columns'=>$dialog->columns(),

		'template'=>$dialog->link()."{summary}\n{items}\n{pager}"));


?>



Hello erand,

Did you ever make it work using the sample code?

Sample code assumptions:

The export button has to find the filters to export, that’s why, in the extension’s sample code, I put the button inside the [font=“Courier New”]_search[/font] partial view, and specifically inside the search form.

Your problem is:

In your code, you put it outside, so the JS code [font=“Courier New”]$(this).parents(‘form’)[/font] returns nothing, neither does [font=“Courier New”]$(this).parents(‘form’).serialize()[/font], which if you put the button inside the form posts the filter to the controller.

Also, you make incorrect use of the $urlJoin variable (you don’t use it in fact).

If you put the button outside the form, you have to pass the form id instead, like this:


$urlJoin = Yii::app()->urlManager->getUrlFormat() == 'path' ? '?' : '&';

Yii::app()->clientScript->registerScript('search', "

$('#exportToExcel').click(function(){

    window.location = '". $this->createUrl('admin')  . $urlJoin . "' + $('#the_id_of_your_form').serialize() + '&export=true';

    return false;

    });

");

My mistake…

Thank you very much for your help/time.

Hi bennouna,

If I sort according to one column, the order is not reflected when exported to excel.

How can I achieve this :) ?

Thank you in advance.

Hello erand,

From what I gather from CGridView documentation, I can’t see how to catch natively the sorting event or values (which column is clicked and which order is applied).

I haven’t searched the forum either for a similar situation, and I guess you did / you’ll do.

Anyway, I can see at least a way of hacking it:

[list=1]

[*]In the JS export click event handler: before submitting the form, looping through the $(“a.sort-link”) elements and checking whether they have a “desc” or “asc” class, and if it’s the case, adding that information to the submit data,

[*]In the controller, you have to make sure to pass that data to the model,

[*]In the model search method, you have to check again for that sort data to apply it where applicable.

[/list]

I’m curious what you’ll find, and I hope you post your findings ;)

Hi bennouna,

Thank you for your reply.

I got it working by setting the ordering as a filter in advanced search, like this:

In _search:




	<div>

		<?php echo $form->label($model,'Order');?>

		<?php echo $form->dropDownList($model, 'order', $model->columnOrder(),array('empty'=>''));?>

	</div>



In model:




	public function columnOrder(){

		return array(

			'1'=>'Column_1',

			'2'=>'Column_2'

                        //and all the columns I want the user to sort by...

		);

	}







	public function search()

	{

                ...

                ...

                $sort = new CSort();

                

                switch ($this->order){

			case '1':

				$sort->defaultOrder=array('Column_1'=>CSort::SORT_ASC);

				break;

			case '2':

				$sort->defaultOrder=array('Column_2'=>CSort::SORT_ASC);

				break;

			default:

				$sort->defaultOrder=array('some_column'=>CSort::SORT_DESC);	

			}




                $sort->attributes=array(

				//sorting related columns for admin view

					'*'

				);


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

			'sort'=>$sort

		));

        }



and the order is reflected when exported to excel :)

i’m new in yii framework and i need help to export my grid

i use tlbexcelview, follow the instruction but with a different action, view and create new controller. the result it cant export my grid, only search data.

below is my view, export_excel.php




<?php

/* @var $this SatisfactController */

/* @var $model Satisfact */


$this->breadcrumbs=array(

	'Satisfacts'=>array('index'),

	'Manage',

);

$this->menu=array(

	array('label'=>'List Satisfact', 'url'=>array('index')),

	array('label'=>'Create Satisfact', 'url'=>array('create')),

);

$urljoin= Yii::app()->urlManager->getUrlFormat() == 'path' ? '?' : '&';


Yii::app()->clientScript->registerScript('search', "

$('#exportToExcel').click(function(){

		window.location='".$this->createUrl('export').$urljoin."'+

	$(this).parents('export_excel').serialize()+'&export=true';

	return false;

});

$('.search-form form').submit(function(){

	$('#satisfact-grid').yiiGridView('update', {

		data: $(this).serialize()

	});

	return false;

});

");

?>


<h1>Report </h1>

<div class="well" style="">

<?php $this->renderPartial('_searchex',array(

	'model'=>$model,

)); ?>

</div><!-- search-form -->


<?php $this->widget('application.components.widgets.tlbExcelView', array(

    'id'                   => 'satisfact-grid',

    'dataProvider'         => $model->search(),

    'grid_mode'            => $production, // Same usage as EExcelView v0.33

    //'template'           => "{summary}\n{items}\n{exportbuttons}\n{pager}",

    'title'                => 'CS Admin - ' . date('d-m-Y - H-i-s'),

    'creator'              => 'ATK CS',

    'subject'              => mb_convert_encoding('Something important with a date in French: ' . utf8_encode(strftime('%e %B %Y')), 'ISO-8859-1', 'UTF-8'),

    'description'          => mb_convert_encoding('Etat de production généré à la demande par l\'administrateur (some text in French).', 'ISO-8859-1', 'UTF-8'),

    'lastModifiedBy'       => 'Some Name',

    'sheetTitle'           => 'Report on ' . date('m-d-Y H-i'),

    'keywords'             => '',

    'category'             => '',

    'landscapeDisplay'     => true, // Default: false

    'A4'                   => true, // Default: false - ie : Letter (PHPExcel default)

    'RTL'                  => false, // Default: false - since v1.1

    'pageFooterText'       => '&RThis is page no. &P of &N pages', // Default: '&RPage &P of &N'

    'automaticSum'         => true, // Default: false

    'decimalSeparator'     => ',', // Default: '.'

    'thousandsSeparator'   => '.', // Default: ','

    //'displayZeros'       => false,

    //'zeroPlaceholder'    => '-',

    'sumLabel'             => 'Column totals:', // Default: 'Totals'

    'borderColor'          => '00FF00', // Default: '000000'

    'bgColor'              => 'FFFF00', // Default: 'FFFFFF'

    'textColor'            => 'FF0000', // Default: '000000'

    'rowHeight'            => 45, // Default: 15

    'headerBorderColor'    => 'FF0000', // Default: '000000'

    'headerBgColor'        => 'CCCCCC', // Default: 'CCCCCC'

    'headerTextColor'      => '0000FF', // Default: '000000'

    'headerHeight'         => 10, // Default: 20

    'footerBorderColor'    => '0000FF', // Default: '000000'

    'footerBgColor'        => '00FFCC', // Default: 'FFFFCC'

    'footerTextColor'      => 'FF00FF', // Default: '0000FF'

    'footerHeight'         => 50, // Default: 20

    'columns'              =>  //'id',

    						array(

								array('header'=>'No','value'=>'++$row',),

								//'Nilai Kepuasan',

								array('name'=>'message','header'=>'Kritik dan Saran'),

								array('name'=>'satisfact01.name','header'=>'Kepuasan'),

								array('name'=>'user01.username','header'=>'Customer Service'),

								array('name'=>'lokasi'),		

								array('name'=>'create_date','header'=>'Tanggal',//'value'=>"date('dd-MM-yyyy',CDateTimeParser::parse(\$data->create_date, 'dd-MM-yyyy'))", 

								'value'=>'Yii::app()->dateFormatter->format("dd-MM-yyyy",$data->create_date)',

								), // an array of your CGridColumns

))); ?>



below is my controller




.....

	 public function actionExport()

	 {

	 	$model=new Satisfact('search');

	 	$model->unsetAttributes();  // clear any default values

	 	if(isset($_GET['Satisfact'])){

	 	 //$model->attributes=$_GET['Satisfact'];

	 	 $model->user_id=$_GET['Satisfact']['user_id'];

	 	 $model->lokasi=$_GET['Satisfact']['lokasi'];

	 	 $model->from_date=$_GET['Satisfact']['from_date'];

	 	 $model->to_date=$_GET['Satisfact']['to_date'];

	 

	 	}

	 	if (isset($_GET['Satisfact'])) {

	 		$production = 'export';

	 	} else {

	 		$production = 'grid';

	 	}

	 	$this->render('export_excel',array(

	 			'model'=>$model, 'production'=>$production

	 	));

	 }

....



this is my _searchex.php




<?php

/* @var $this SatisfactController */

/* @var $model Satisfact */

/* @var $form CActiveForm */

?>


<div class="wide form">


<?php $form=$this->beginWidget('CActiveForm', array(

	'action'=>Yii::app()->createUrl($this->route),

	'method'=>'get',

		'enableAjaxValidation'=>true,

)); ?>


	<div class="row">

		<?php //echo $form->label($model,'user_id'); ?>

		<?php //echo $form->textField($model,'user_id'); ?>

	</div>

	

	<div class="row">

		<?php echo $form->labelEx($model,'user_id'); ?>

		<?php $_u = User::model()->findAll();

                  echo CHtml::activeDropDownList(

                        $model,'user_id',

                        CHtml::listData($_u,'id','username'),

                        array('prompt'=>'',) //empty is aliases FOR ALL user

					);

               ?>

	</div>

	

	<?php echo $form->labelEx($model,'lokasi'); ?>

		<?php $lo_u = Lokasi::model('Lokasi')->findAll('id');

                  echo CHtml::activeDropDownList(

                        $model,'lokasi',

                        CHtml::listData($lo_u,'location','location'),

                        array('prompt'=>'',)//empty is aliases FOR ALL lokasi

					);

               ?>


	<div class="row">

		<?php //echo $form->label($model,'lokasi'); ?>

		<?php //echo $form->textField($model,'lokasi',array('size'=>25,'maxlength'=>25)); ?>

	</div>


	<div class="column">

		<?php echo $form->label($model,'create_date'); ?>

		<?php //echo $form->textField($model,'create_date'); ?>

		<?php 

		echo "From : ";

			$this->widget('zii.widgets.jui.CJuiDatePicker',

			array(

			'name'=>'Satisfact[from_date]',

			'options'=>array('dateFormat'=>'yy-mm-dd',),			


			));

		echo " To : ";

			$this->widget('zii.widgets.jui.CJuiDatePicker',

			array(

			'name'=>'Satisfact[to_date]',

			'options'=>array('dateFormat'=>'yy-mm-dd',),			

			

			));	

		

		

		?>

	</div>


	<div class="row buttons">

		<?php //echo CHtml::submitButton('Search'); ?>

		<?php echo CHtml::submitButton('Export',array('id' => 'exportToExcel')); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- search-form -->




how can I find and to export the data search ?