?
Solved

Could you point how to use moment.min.js  to be used in conjunction with datatables plugin?

Posted on 2016-11-04
6
Medium Priority
?
218 Views
Last Modified: 2016-11-12
Hi Experts


Accordingly with some researchs a way to correctly configure date(s) when using datatables is with moment.min.js

So, folowing the examples:

Considering a Codeigniter's helper outputs to the view.

Helper's code that forms datatable

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

if (!function_exists('datatables_padrao2'))
{


    function datatables($fields, $options, $search)
    {


        $order = $cont = 4;
        $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>
            
            <!-- Moment declaration -->
            <script src="' . base_url() . 'public/vendor/plugins/moment/moment.min.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(){

                  // Is here the correct place to declare ?
                  $.fn.dataTable.moment( "DD/MM/YYYY hh:mm");


                $("#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 projeto-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



Error founded:
img004

Could you check and give a help?

Thanks in advance.
0
Comment
Question by:Eduardo Fuerte
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
6 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 41874279
please share a link to your page, you will increase help.
1
 

Author Comment

by:Eduardo Fuerte
ID: 41874748
Hi leakim971

This site is still intranet.
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 2000 total points
ID: 41875060
you need to include this : http://cdn.datatables.net/plug-ins/1.10.9/sorting/datetime-moment.js after your line 45

            <!-- Datatable Moment declaration -->
            <script src="' . base_url() . 'your/path/to/datetime-moment.js"></script>

Open in new window


/**
 * This plug-in for DataTables represents the ultimate option in extensibility
 * for sorting date / time strings correctly. It uses
 * [Moment.js](http://momentjs.com) to create automatic type detection and
 * sorting plug-ins for DataTables based on a given format. This way, DataTables
 * will automatically detect your temporal information and sort it correctly.
 *
 * For usage instructions, please see the DataTables blog
 * post that [introduces it](//datatables.net/blog/2014-12-18).
 *
 * @name Ultimate Date / Time sorting
 * @summary Sort date and time in any format using Moment.js
 * @author [Allan Jardine](//datatables.net)
 * @depends DataTables 1.10+, Moment.js 1.7+
 *
 * @example
 *    $.fn.dataTable.moment( 'HH:mm MMM D, YY' );
 *    $.fn.dataTable.moment( 'dddd, MMMM Do, YYYY' );
 *
 *    $('#example').DataTable();
 */

(function($) {

$.fn.dataTable.moment = function ( format, locale ) {
	var types = $.fn.dataTable.ext.type;

	// Add type detection
	types.detect.unshift( function ( d ) {
		// Null and empty values are acceptable
		if ( d === '' || d === null ) {
			return 'moment-'+format;
		}

		return moment( d.replace ? d.replace(/<.*?>/g, '') : d, format, locale, true ).isValid() ?
			'moment-'+format :
			null;
	} );

	// Add sorting method - use an integer for the sorting
	types.order[ 'moment-'+format+'-pre' ] = function ( d ) {
		return d === '' || d === null ?
			-Infinity :
			parseInt( moment( d.replace ? d.replace(/<.*?>/g, '') : d, format, locale, true ).format( 'x' ), 10 );
	};
};

}(jQuery));

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:Eduardo Fuerte
ID: 41878599
Hi @leakim971

You pointed the right way!

But something is preventing the datatables plugin grid to be loaded.

$(document).ready(function(){

	  //The js call - no error
	  $.fn.DataTable.moment( "DD/MM/YYYY hh:mm");
	  ...

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 41878689
be sure to add the plugin in the right order.
post the file you're using, of course you need the moment.js too somewhere (custom dataTable plugin or not)
0
 

Author Closing Comment

by:Eduardo Fuerte
ID: 41884919
Thanks for help!
0

Featured Post

Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

752 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