ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Ignited DataTables

July 15, 2010 2:51am

Subscribe [119]
  • #196 / Jul 18, 2011 12:21pm

    ηυмвєяσηє

    109 posts

    Hi,

    $this->load->helper("Datatables"); // create datatables_helper.php in helpers folder
    $this->load->library("Datatables");
    ..
    ..
    ->edit_column('jobstatus', "".base_url().", 'callback_getjobstatus(jobstatus)' )
    ->edit_column('level', "".base_url().", 'callback_getjoblevel(level)');

    // add these functions to datatables_helper.php

    function getjobstatus ($jobstatus) {
     if($jobstatus == "T")
       return "icons/accept.png";
     elseif($jobstatus == "A")
       return "ico_stop_16.png";
     else
       return "ico_inactive_16.png";
    }
    
    function getjoblevel ($level) {
          return ($level == "I")? "incBackup.png" : "fullBackup.png";
    }

    (strongly advised to do this in javascript, if you can)


    About ‘GROUP BY’, I thought this before, However It is better to use the code below for some reasons.

    you should use ‘GROUP BY’ in subqueries.

    For Example :

    $this->load->library("Datatables");
    
    $this->datatables
     ->select('pages.id as pageid, title')
     ->from('(SELECT id,title,user_id FROM pages GROUP BY user_id) as pages')
     ->join('users', 'users.id = pages.user_id', 'left' )
     ->select('username');
    
    echo $this->datatables->generate();

    its not a very good example but i think u got the idea ^^

    Regards,
    Yusuf

  • #197 / Jul 18, 2011 6:59pm

    lordoffriends

    5 posts

    How to override the Query string parameter in editable datagrid ?The default query string is generated by the datagrid(i.e adding an id parameter which has the value of the first column cell of the datatable).When i click on the specific row,and click on the delete button,the delete url is called as given in the code.This url is initialized in the code.What i want to ask is ,how do i override the url at runtime(i.e adding my row data specific query string in the url) ????

    This is the code i am using…
    ————————————————————————————————————

    $(document).ready( function () {
    oTable=$('#example').dataTable({
    "bProcessing": true,
    "sAjaxSource": "http://localhost/questions/Test/listener",
    "fnInitComplete": function (){
    $(oTable.fnGetNodes()).click(function (){
    var aPos = oTable.fnGetPosition( this );
    var aData = oTable.fnGetData( aPos[0] );
    });
                    },
              aoColumns: [ { "bVisible": false} , null, null, null, null ]
                          }
                          ).makeEditable({
    sUpdateURL: "UpdateData.php",
    sAddURL: "AddData.php",
    sAddHttpMethod: "GET",
    sDeleteURL: "http://localhost/questions/Test/DeleteData",
    sDeleteHttpMethod: "GET",
    });
          } );
    —————————————————————————————————-

    Waiting for reply.

  • #198 / Jul 18, 2011 11:14pm

    cryogenix

    90 posts

    although your question is datatables specific, we’re kind enough to answer you 😉

    take note of the submitdata parameter here: http://www.datatables.net/examples/api/editable.html

    with that in mind, you can do some editing like this:

    'submitdata':
            function(value, settings)
            {
              var k = -1, e = this, column;
    
              while(e){
                if('previousSibling' in e)
                {
                  e = e.previousSibling;
                  k = k + 1;
                }
                else
                {
                  k = -1;
                  break;
                }
              }
    
              switch(k)
              {
                case 1 : column = 'name'; break;
                case 2 : column = 'email'; break;
                default: column = 'password'; break;
              }
    
              return { 'column' : column, 'operator_id' : this[removed].firstChild[removed] }
            }
  • #199 / Jul 19, 2011 6:07am

    pmsfo

    13 posts

    For the images what i did was this

    $this->datatables->edit_column('job.level', '.base_url().', 'job.level');

    and change the name of file.

    For example i only have 2 types of jobs levels “I” and “F” so i change the filename from incBackup.png for I.png and F.png.

    i think in this case its better than creating a database helper.

    But it’s nice to know that is possible to create helpers and using functions.

    thank you very much for you r reply

  • #200 / Jul 21, 2011 6:19pm

    lordoffriends

    5 posts

    This is the code…

    var oTable;
    var aData;
    var row;

    $(document).ready(function() {

    $('#example tbody tr').live('click', function (event) {

    $(oTable.fnSettings().aoData).each(function (){
    $(this.nTr).removeClass('row_selected');
    });

            $(event.target[removed]).addClass(‘row_selected’); 
            aData = oTable.fnGetData(this); // get datarow
            row = $(this).closest(“tr”).get(0);
          });

            /* Add a click handler for the delete row */
              $(’#delete’).click( function() {
    $.ajax({
    type: "GET",
    url: "<?php echo base_url(); ?>Test/DeleteData",
    data: "id="+aData[0],
    success: function(msg){
    //oTable.fnDeleteRow(aData);
    var anSelected = fnGetSelected( oTable );
    oTable.fnDeleteRow( anSelected[0] );
    oTable.fnDeleteRow(oTable.fnGetPosition(row));
    }
            });   
              } );

            /* Init the table */
              oTable = $(’#example’).dataTable( {
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "<?php echo base_url(); ?>Test/Listener",
    "sPaginationType": "full_numbers",
    "iDisplayLength": 1,
    "bSortClasses": false,
    "aoColumns": [ { "bVisible": false} , null, null ]
              } ); 


            } ); 
            /* Get the rows which are currently selected */
            function fnGetSelected( oTableLocal )
            {
    var aReturn = new Array();
    var aTrs = oTableLocal.fnGetNodes();

    for ( var i=0 ; i<aTrs.length ; i++ )
    {
    if ( $(aTrs).hasClass('row_selected') )
    {
    aReturn.push( aTrs );
    }
              }
              return aReturn;
            }
    What is happening :-
    The server side data gets loaded when page is called for the first time.
    The server side data gets deleted on clicking delete link.But the Datatable doesnt refresh after deleting a row on server.The usual “processing” message comes after deletion on server.It stays there.The UI row stays there highlighted with message “Processing” in the middle of the page

    What i have observed is :-
    1)The response of Ajax source after the delete url is called is this :-
    {"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":[["11","PD101-DH1234","adsasd"]],"sColumns":"PartId,PartNumber,PartDescription"}
    2)After using firebug,i observed no abnormalities.Both the delete and get source requests are executed perfectly with response OK.
    3)I am using FireFox 4.1
    4)I am using DataTables 1.8.1 build.

    Now Question :-
    What do i change in the above code so that the datatable UI row gets deleted and datatable refreshes to bring the remaining rows ???

  • #201 / Jul 22, 2011 5:51pm

    lordoffriends

    5 posts

    Everything is working now.

  • #202 / Jul 26, 2011 4:31am

    cryogenix

    90 posts

    made a small update which may be great news to some.

    added foreign charset support for generating results.

    so these are now possible:

    //generate with default utf-8 encoding
    $this->datatables->generate();
    
    //generate with latin-1 character support
    $this->datatables->generate('ISO-8859-1');

    i hope some of you may find this useful (as i did at work today).

  • #203 / Jul 27, 2011 1:18pm

    jtrainaldi

    24 posts

    I was wondering if I can pass a controller function into the add_column parameter.  The function called queries a separate database and prints out a string based on whether there is data in the table or not.

    $this->datatables
                ->select('id, employee_name, submitted_date')
                ->from('wc_table')
                ->add_column('related_info', $this->printRelateInfo($id), 'id')
            ;        
    
    
    function printRelateInfo($id){
      $str = '';
    
      //Get the employee data
      $employee_data = $this->employee_model->getEmployeeData($id);
      if(sizeof($employee_data)==0):
         $str .= '<a- href="#" class="disabled-link">form.png</a>';
      else :
        $str .= '<a- href="viewInfo/$employee_data[0] ['id']">form.png</a>';
      endif;
      
      echo $str;
    
    }
  • #204 / Jul 29, 2011 1:50am

    cryogenix

    90 posts

    don’t echo it in the function. return it instead:

    $this->datatables
         ->select('id, employee_name, submitted_date')
         ->from('wc_table')
         ->add_column('related_info', $this->printRelateInfo($id), 'id');        
    
    function printRelateInfo($id)
    {
      $str = '';
    
      //Get the employee data
      $employee_data = $this->employee_model->getEmployeeData($id);
    
      if(sizeof($employee_data)==0):
        $str .= '<a href="#" class="disabled-link">form.png</a>';
      else:
        $str .= '<a href="http://viewInfo/$employee_data0">['id']"]form.png</a>';
      endif;
    
      return $str;
    }
  • #205 / Aug 01, 2011 2:24am

    Derek Nutile

    3 posts

    In your example above, how does the printRelateInfo function know what the variable $id is?  Shouldn’t it be more like a back reference like the code below?  I can’t get that to work either though, so any help would be appreciated.

    ->add_column('related_info', $this->printRelateInfo('$1'), 'id');
  • #206 / Aug 02, 2011 5:58am

    cryogenix

    90 posts

    i just copied your code and didn’t notice that…

    my point was about returning the result instead of an echo.

    adjust code as you see fit =)

  • #207 / Aug 02, 2011 2:35pm

    Sakacoco

    1 posts

    Hey there, thanks a lot for this plugin, very useful but, like the last posts, I’m trying to add a function when editing/adding a column and it fails miserably, I only obtain “no” in every rows, could you help me a bit ?

    function userlist()
        {
            $this->load->library('datatables');
            $this->datatables
                    ->select("login, email, activation")
                    ->from('users')
                    ->edit_column('activation', $this->show_activation_link('$1', '$2'), 'activation, login');
            echo $this->datatables->generate(); 
        }
        private function show_activation_link($status, $user)
        {
            if($status == 0)
            {
                return "no";
            }
            elseif($status == 1)
            {
                return "yes";
            }
        }
  • #208 / Aug 02, 2011 8:21pm

    Derek Nutile

    3 posts

    My method uses active record.  Here’s a test method:

    function datatable_test ()
    {
        $query = $this->db->select('state_name');
        $query = $this->db->get('states');
    
        return = "Some output ...";
    }

    When I call this method with the Datatables library, like this:

    $this->datatables
            ->select('id, member_id, user_name, state')
            ->edit_column('state', $this->customer_model->datatable_test('$1'), 'id')
            ->from('orders');
    echo $this->datatables->generate();

    The result is a database error on the JSON page like this.  Notice it has combined the fields from the datatables SQL with the datatable_test method:

    Unknown column ‘state_name’ in ‘field list’
    SELECT id, member_id, user_name, state_name FROM (states) WHERE `statecd` = ‘OR’

    I assume this is because the library creates it’s own CI object, but maybe you can clarify.

    Note that I am making this simple.  Of course my method doesn’t just get the state for a user or I would create a JOIN.  Instead, my method iterates through several stages to get an order status based on many variables.

  • #209 / Aug 03, 2011 4:08am

    ηυмвєяσηє

    109 posts

    First, you can not use ‘edit_column’ like :

    ->edit_column('state', $this->customer_model->datatable_test('$1'), 'id')

    The second parameter must be a string. it is not possible to use functions in a controller in order to use ‘$1’ value. You need to use a helper function instead of that and you need to use that as a callback function.

    example of using a helper:
    1. Create a helper file in your helper directory (datatables_helper.php)


    2. Load your helper (datatables_helper.php) in your ajax listener.

    function listener()
        {
          $this->load->helper("Datatables"); // create datatables_helper.php in helpers folder
          $this->load->library("Datatables");
          $this->datatables
            ->select('id, name, email, age, status')
            ->from('tbl_profile')
            ->edit_column('name', '$1', 'strtolower(name)')  // php functions
            ->edit_column('email', '$1', 'customfunction(id, email, status)');  //custom functions in your helper..
          $data['result'] = $this->datatables->generate();
          $this->load->view('ajax', $data);
        }

    3. Use SQL ‘JOIN’ statement as u can. Performance will be reduced, even if you did a function like below. Because, it runs a query at every row.

    function datatable_test ()
    {
        $query = $this->db->select('state_name');
        $query = $this->db->get('states');
    
        return = "Some output ...";
    }


    Regards,
    Yusuf

  • #210 / Aug 03, 2011 5:41pm

    Derek Nutile

    3 posts

    Exactly what I needed Yusuf, thanks!