Jumat, 04 Februari 2022

Datatable: set title to downloaded File

 Short post, in case I need it later. 

So my problem was, I have several datatables in one page and each datatable has download buttons. Normaly, datatable will use the page's title as the name of the downloaded file. But I have more than one datatables and I want the downloaded file has different name. 

And here is the solution.


$('#zero_configuration_table').DataTable( {
	dom: 'Bfrtip',
	buttons: [
		{extend:'excelHtml5', title: 'Dashboard Tracer Study'},
        {extend:'pdfHtml5', title: 'PDF Dashboard Tracer Study'}
	],
	scrollX:        true,
	scrollCollapse: true,
	paging:         false,
	fixedColumns: false,
	autoWidth: false,
});

Take a look at the buttons, simple right. I can even put different name on each button. With that code, the datatables doesn't do pagination and it is horizontally scrollable.

Datatable : Adding a Row Dynamically and adding its atrribute

Ok, I had a problem to solve the problem I mentioned in the title of this post. 

So, I combined two solution from two sources (Actually I've browsed to several websites and discussions). 

These are my sources: Source 1, Source 2.

I use ajax to retrieve the data and then add them dynamically to the table. Then, I want to align the text to center and add onclick event on each row.

So here is my Table:


<div class="table-responsive">
	<table class="table table-striped table-bordered" 
    	id="transaction_detail" cellspacing="0" width="100%">
		<thead>
			<tr class="text-center align-middle">
				<th>Name</th>
				<th>email</th>
				<th>Phone</th>
				<th>Transactions</th>
				<th>Turnover</th>

			</tr>
		</thead>
		<tbody >

				
		</tbody>
	</table>
</div>


And here is my Ajax:


$.ajax({
  type:"POST",
  url:"/gettransaction",
  data:{customer_id: customerid},
  success:function(data){
	var jsondat = JSON.parse(data)  ;
	
	//clear the table's body
	$("#transaction_detail").DataTable().clear().draw();

	if(jsondat.length > 0){
		for(var i=0; i<jsondat.length; i++){
			
			var rowTab = $("#transaction_detail")
				.DataTable()
				.row
				.add([
				jsondat[i].customer_name,
				jsondat[i].customer_address,
				jsondat[i].customer_phone,
				jsondat[i].number_transaction,
				jsondat[i].turnover
			]);


			//use node() so that row is editable.
			var rowEdit = rowTab.node();

			$(rowEdit).attr("style", 
				"cursor:pointer; text-align:center");
			$(rowEdit).attr('onclick',
            	"showTrans("+jsondat[i].customer_id+")");

			//redraw the table after its modified
			rowTab.draw(false);
		}   

	}
  },
  error: function(){

  }
});


I hope it can help you somehow. cheers!!