Solved

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

Posted on 2016-11-04
6
64 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
  • 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 500 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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

757 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

19 Experts available now in Live!

Get 1:1 Help Now