Solved

Could you point the correct place to embed a Datatables Bootstrap plugin  on this existing code to have column filter feature?

Posted on 2016-09-28
13
90 Views
Last Modified: 2016-10-13
Hi Experts

Could you point the correct place to embed a Datatables Bootstrap plugin  on this existing code to have column filter feature?

I need to put a filter in an existing "Datatables"  Bootstrap plugin, acordingly to that:

img003o

Datatables site suggest to put this code to complete this task

$(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );
 
    // DataTable
    var table = $('#example').DataTable();
 
    // Apply the search
    table.columns().every( function () {
        var that = this;
 
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );

Open in new window


My problem is how to embed this in this existing code:
	
		function datatables($fields, $options, $search) {

			$order = $cont = 0;
			$order_type = "asc";
			
			if(isset($options['order'])) {
			
				if(isset($options['order_type']) && $options['order_type'] == 'desc')
					$order_type = 'desc';
				
				foreach($fields as $field => $label) {
					
					if($options['order'] == $field) {
						$order = $cont;
					}

					$cont++;
				}


			}

			$datatables = '
				<link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.bootstrap.css">
				<link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.plugins.css">

				<script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/jquery.dataTables.js"></script>
				<script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/dataTables.bootstrap.js"></script>
				';

			if (!isset($options['id']))
				$options['id'] = 'datatables_ajax';

			if (!isset($options['search_submit']))
				$options['search_submit'] = '.search_submit';

			$datatables .= '

			<script type="text/javascript">

				$(document).ready(function(){

					$("#pesquisar_groups_form").on("submit",function(){

						// não submete pagina - dont reload
						return false;

					});
					
					$(".clear_pesquisa").on("click",function(){

						// $("#pesquisar_groups_form").trigger("reset");
						redrawDataTables("");
					});

					redrawDataTables("");

					$("'.$options['search_submit'].'").on("click", function (e) {

						var table = "";
						var where = {';

							if (isset($search['like'])) {

								$datatables .= '"like" : {';

								$cont = 0;
								foreach($search['like'] as $val) {

									if($cont == 0)
										$datatables .= '"'.$val.'" : $("#pesquisar_groups_form").find("#'.$val.'").val()';
									else
										$datatables .= ',"'.$val.'" : $("#pesquisar_groups_form").find("#'.$val.'").val()';

									$cont++;

								}
								$datatables .= '}';

								if (isset($search['where']))
									$datatables .= ',';

							}

							if (isset($search['where'])) {

								$datatables .= '"where" : {
									';

								$cont = 0;
								foreach($search['where'] as $val) {

									if($cont == 0)
										$datatables .= '"'.$val.'" : $("#pesquisar_groups_form").find("#'.$val.'").val()
									';
									else
										$datatables .= ',"'.$val.'" : $("#pesquisar_groups_form").find("#'.$val.'").val()
									';

									$cont++;

								}
								$datatables .= '}
								';
							}

						$datatables .= '}
						';
						
						$datatables .= '

						redrawDataTables(where);
					});
				});

				function redrawDataTables(where) {



					if (typeof table != "undefined" && typeof table != undefined && table != "") {

						$("#exemplo").empty();
						table.destroy();
					}

					if (typeof where == "undefined" || typeof where == undefined) {
						where = "";
					}

					table =  $("#' . $options['id'] . '").DataTable({
						"paging":   true,
						// "pagingType": "scrolling",
						"pagingType": "full_numbers",
						// "sPaginationType": "four_button",
						"retrieve": true,
						"searching": false,
						"ordering": true,

						"order": [
							[ 
								'.$order.', "'.$order_type.'"
							]
						],

						aaSorting: [],

						"lengthChange": false,
						"info": false,
						"ajax": {
							"url": "' . base_url() . $options['controller'] . '/' . $options['action'].'",
							"type": "post",
							"data": where,
							"processing": true,
						},
						"language": {
							"sEmptyTable": "Nenhum registro encontrado",
							"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
							"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
							"sInfoFiltered": "(Filtrados de _MAX_ registros)",
							"sInfoPostFix": "",
							"sInfoThousands": ".",
							"sLengthMenu": "_MENU_ resultados por página",
							"sLoadingRecords": "Carregando...",
							"sProcessing": "Processando...",
							"sZeroRecords": "Nenhum registro encontrado",
							"sSearch": "Pesquisar",
							"oPaginate": {
								"sNext": "",
								"sPrevious": "",
								"sFirst": "",
								"sLast": ""
							},
							"oAria": {
								"sSortAscending": ": Ordenar colunas de forma ascendente",
								"sSortDescending": ": Ordenar colunas de forma descendente"
							}
						}
					});

					$("#datatables tr").addClass("tr_clicked meeta-cursor-pointer");
				}
			</script>';

			 $datatables .= '

				<style>
					.pagination > li:last-child > a{
						z-index: 0;
					}
					.input-group {
						z-index: 0;
					}
				</style>';

				$datatables .= '

				<table id="' . $options['id'] . '" class="table admin-form theme-warning fs13" cellspacing="0" width="' . $options['width'] . '">
					<thead>
						<tr>';

					if(array_key_exists('active_ind',$fields))
						$fields = array_merge($fields, array('acoes'=>'Ações'));

					foreach ($fields as $field => $title) {
						$datatables .= '<th>' . $title . '</th>';
					}

				$datatables .=
						  '</tr>
						</thead>
					</table>';

			return $datatables;
		}

Open in new window


Thanks in advance!
0
Comment
Question by:Eduardo Fuerte
  • 8
  • 5
13 Comments
 
LVL 24

Expert Comment

by:lenamtl
Comment Utility
Hi,
which datatable version are you using as old and new version are completely different syntax
check the version in datatable.js file.

I'm using  datatble  a lot and their filter function is not very flexible
with template

Are you using server side or client side filtering?

You may like to check this datatable plugin yadcf
https://github.com/vedmack/yadcf
0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
Sorry


I just omit the {  } in the jquery else. That's the problem.
 if (serv != 'Sim')
            {
                $(".custo").hide();
                $("#divReembolso").hide();
            }         
            else
            {
                $(".custo").show();
                $("#divReembolso").show();
            }

Open in new window


It runs that way
0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
Hi lenamtl

Sorry again, I misconcept the questions!

I'm going to check your reply carefully.
0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
Hi

My problem here is where to put the code suggested in Datatables plugin site inside my existing code.
0
 
LVL 24

Expert Comment

by:lenamtl
Comment Utility
Which datatable.js version are you using?

Based on their example found at
https://datatables.net/examples/api/multi_filter.html
You need to use the provided code for each part js, html, CSS

Don't forget the CSS part
tfoot input {
        width: 100%;
        padding: 3px;
        box-sizing: border-box;
    }

Open in new window


this js part is can be replaced by your datatable code
 // DataTable
    var table = $('#example').DataTable();

Open in new window


You can tried with this basic example to test it, then apply to your code.
This should work and your code seems ok too, but it's hard to say without seen the page...

Check with Chrome dev tool if there is any error (rigth click Inspect).
0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
Hi

I'm not sure what is the correct version, based on:
img003
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 24

Expert Comment

by:lenamtl
Comment Utility
You are looking in the wrong directory
you checked in the extension directory
instead you need to check in datatable directory
vendor/plugins/datatables
and find datatable.js
0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
I couldn't find datatable.js at the folder you pointed:

img001
0
 
LVL 24

Accepted Solution

by:
lenamtl earned 500 total points
Comment Utility
this may depends of the template you are using

in my case i'm using these latest datatables  with Bootstrap  & responsive
js/plugins/datatables/media/
<script src="js/plugins/datatables/media/js/jquery.dataTables.min.js"></script>
<script src="js/plugins/datatables/media/js/dataTables.bootstrap.min.js"></script>

js/plugins/datatables/extensions/
<script src="js/plugins/datatables/extensions/Responsive/js/dataTables.responsive.min.js"></script>
<script src="js/plugins/datatables/extensions/Responsive/js/responsive.bootstrap.min.js"></script>
0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
Hi

Here it is

img003
0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
We are using:

$datatables = '
            <link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.bootstrap.css">
            <link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.plugins.css">

            <script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/jquery.dataTables.js"></script>
            <script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/dataTables.bootstrap.js"></script>
            ';

Open in new window


Something changes?
0
 
LVL 24

Expert Comment

by:lenamtl
Comment Utility
Can you create a codepen so we can see the problem?

Here is another way to do it
https://codepen.io/sfauch1/pen/YGWGyN
0
 

Author Comment

by:Eduardo Fuerte
Comment Utility
Thanks lenamtl

I'm going to follow the steps you pointed.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now