Solved

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

Posted on 2016-11-04
6
98 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

773 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