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.

Flexigrid - Lightweight but rich data grid

March 28, 2008 10:13am

Subscribe [82]
  • #331 / May 20, 2008 12:25pm

    ozskry

    10 posts

    Another question: is it possible to show images inside the table? I want to show products previews.

    Cheers,
    Cary

  • #332 / May 20, 2008 12:48pm

    swhitlow

    22 posts

    paulopmx - thanks for the response. Although my main problem was that nothing was showing up in firebug to trace anything. So, no errors were occurring.

    However, I was able to find the root of the problem. This is just for anyone else who would want to know - the problem was with prototype. I had a prototype library being loaded. I did have the jquery noConflict mode on but for some reason, it still did not want to cooperate with Flexigrid. If anyone knows a way to have prototype and Flexigrid working together, that would be great.

    For now, I have just removed the prototype reference and have been working around it.

  • #333 / May 20, 2008 4:48pm

    SeanRock

    4 posts

    Hey Paulo,

    $('#flex1').flexOptions({newp:1});

    Fixed my paging problem.

    A couple questions for you.

    1) Is it possible to set the table to only select one row?
    2) How do I add an event to a row being selected/deselected?
    </code></pre>

    i’ve modifed the flexigrid.js to fire a onRowSelected event that passes the id of the row, the actual row and the grid. it was suprisingly easy to implement.

    i’m going to look at creating a ‘multi-select’ and ‘single-select’ option - (time permitting).

    [edit]

    wow thanks to Paulo’s excellent work - implementing a singleSelect was so easy. if anyone is interested reply and i’ll post the code here.

    regards
    Sean

  • #334 / May 20, 2008 8:46pm

    paulopmx

    164 posts

    paulopmx - thanks for the response. Although my main problem was that nothing was showing up in firebug to trace anything. So, no errors were occurring.

    However, I was able to find the root of the problem. This is just for anyone else who would want to know - the problem was with prototype. I had a prototype library being loaded. I did have the jquery noConflict mode on but for some reason, it still did not want to cooperate with Flexigrid. If anyone knows a way to have prototype and Flexigrid working together, that would be great.

    For now, I have just removed the prototype reference and have been working around it.

    This must be the same problem encountered with mootools, where mootools is ‘extending’ all native objects and methods. I will look in to this in my next release.

  • #335 / May 20, 2008 8:48pm

    paulopmx

    164 posts

    Hey Paulo,

    $('#flex1').flexOptions({newp:1});

    Fixed my paging problem.

    A couple questions for you.

    1) Is it possible to set the table to only select one row?
    2) How do I add an event to a row being selected/deselected?
    </code></pre>

    i’ve modifed the flexigrid.js to fire a onRowSelected event that passes the id of the row, the actual row and the grid. it was suprisingly easy to implement.

    i’m going to look at creating a ‘multi-select’ and ‘single-select’ option - (time permitting).

    [edit]

    wow thanks to Paulo’s excellent work - implementing a singleSelect was so easy. if anyone is interested reply and i’ll post the code here.

    regards
    Sean


    Great job Sean.

    jQuery is pretty easy just like CodeIgniter.

  • #336 / May 20, 2008 9:33pm

    Czarchaic

    5 posts

    Hello all. I’ve been fascinated by this plugin for the last couple of days and I stumbled into this forum. I took some existing code I’ve been using and modified it for a very straight forward example of the use of this awesome plugin with CI. Excellent work Paulo!
    The DB

    <?php   // CREATE TABLE `dbname`.`homes` (
        // `id` INT( 10 ) NOT NULL AUTO_INCREMENT ,
        // `price` FLOAT( 14 ) NOT NULL ,
        // `sqft` FLOAT( 10 ) NOT NULL ,
        // `bedrooms` INT( 2 ) NOT NULL ,
        // `pool` INT( 1 ) NOT NULL ,
        // `description` VARCHAR( 250 ) NOT NULL ,
        // PRIMARY KEY ( `id` )
        // ) ENGINE = MYISAM 
    ?>

    The Model
    homesmodel.php

    <?php
    class Homesmodel extends Model {
    
    
    
    
        function __construct() {
            parent::Model();
        }
    
    /* RETURNS AN ARRAY WITH TWO ITEMS
            'homes'=> THE RESULT OBJECT     
            'total'=> NUMBER OF TOTAL RESULTS OF THE QUERY WITHOUT LIMIT AND OFFSET */
    
        function fetch_homes($sortname='price',$sortorder='desc',$limit=10,$offset=1,$query=null,$qtype=null) {
    
        $this->db->from('homes');
        $this->db->order_by($sortname,$sortorder);
        
        if(! is_null($query)) {
        
            /* GET TOTAL ROWS BEFORE THE LIMIT */
            $this->db->like($qtype,$query);
            $total = $this->db->get()->num_rows();
            
            /* RESET THE DB QUERY SINCE IT WAS ALREADY USED */
            $this->db->like($qtype,$query);
        }
        
        else {//NO QUERY
        $total = $this->db->get()->num_rows();
        }
            /* RESET THE DB QUERY*/
            $this->db->from('homes');
            $this->db->order_by($sortname,$sortorder);
            $this->db->limit($limit,$offset);
            $q = $this->db->get();
            $arr = array('homes'=>$q,'total'=>$total);
            return $arr;
    }
        
    }
    ?>

    The View
    view_homes.php

    <?php 
    /* CODE IGNITER, JQUERY FLEXIGRID DEMO
    WITH JSON TABLE UPDATING AND SEARCH */
    
    /* LOAD THE FLEXIGRID STYLESHEET */
    echo link_tag('css/flexigrid.css');
    echo link_tag('css/homes.css');?>
    
    
    <!-- THE FLEXIGRID TABLE -->
    <table id="flexigrid_homes"></table>
    
    <!-- LOAD JQUERY AND FLEXIGRID -->
    
    
    
    
    <!-- script-->
        
    function alertSelected() {
        var alert_text = '';
        var selected_rows = $("table#flexigrid_homes").find("tr.trSelected").get();
        if(selected_rows.length > 0) {
            alert_text = 'You selected the following row ids:' ;
        }
        else {
            alert_text = 'You did dnot select any rows';
        }
        $.each(selected_rows,function(i,n) {
            var id = $(n).attr("id");
            alert_text += id.substr(3)+", ";
        });
        alert(alert_text);
        /* console.log〈alert_text); */
    }
    
    function selectAll() {
        var rows = $("table#flexigrid_homes").find("tr").get();
        if(rows.length > 0〉 {
        $.each(rows,function(i,n) {
            $(n).addClass("trSelected");
        });
        }
    }
    
    function deselectAll() {
        var selected_rows = $("table#flexigrid_homes").find("tr").get();
        if(selected_rows.length > 0) {
        $.each(selected_rows,function(i,n) {
            $(n).removeClass("trSelected");
        });
        }
    }
    
    function invertSelection() {
        var rows = $("table#flexigrid_homes").find("tr").get();
        $.each(rows,function(i,n) {
            $(n).toggleClass("trSelected");
        });
    }
    
    function bind_single_select() {
      if ( ! $("input#single").length>0) {
        $("span.single_select").prepend("<input type='checkbox' name='single' id='single' />");
      }
    $("table#flexigrid_homes").find("tr").click(function() {
            if($("input#single").attr("checked")) {
                $(".trSelected").removeClass("trSelected");
                $(this).addClass("trSelected");
            }
            });
    }
    $(document).ready(function() {
                $("table#flexigrid_homes").flexigrid({
                url: '/CI_BASE/index.php/homes/flex',
                dataType: 'json',
                colModel : [
                    {display: 'Id', name : 'id', width : 40, sortable : true, align: 'left'},
                    {display: 'Description', name : 'description', width : 300, sortable : true, align: 'left'},
                    {display: 'Price', name : 'price', width : 100, sortable : true, align: 'left'},
                    {display: 'Square Footage', name : 'sqft', width : 100, sortable : true, align: 'right'},
                    {display: 'Bedrooms', name : 'bedrooms', width : 100, sortable : true, align: 'right'},
                    {display: 'Pool', name : 'pool', width : 30, sortable : true, align: 'center'},
                    ],
                searchitems : [
                    {display: 'Description', name : 'description', isdefault: true},
                    ],
                buttons : [
                    {name: 'Alert Selected', bclass: 'alert_selected',onpress: alertSelected},
                    {separator: true},
                    {name: 'Select All', bclass: 'alert_selected',onpress: selectAll},
                    {name: 'Deselect All', bclass: 'alert_selected',onpress: deselectAll},
                    {name: 'Invert Selection', bclass: 'alert_selected',onpress: invertSelection},
                    {separator: true},
                    {name: 'Single Select', bclass: 'single_select',onpress: bind_single_select},
                    ],
                sortname: "price",
                sortorder: "desc",
                usepager: true,
                title: 'Homes',
                procmsg: "Searching the MASSIVE homes database",
                useRp: true,
                rp: 5,
                rpOptions: [5,10,20,50],
                showTableToggleBtn: true,
                height: '150',
                onSuccess: bind_single_select
            });
    
    });

    Next post the Controller

  • #337 / May 20, 2008 9:42pm

    Czarchaic

    5 posts

    The Controller
    homes.php

    <?php
    class Homes extends Controller {
        function __construct() {
            parent::Controller();
            
            /* LOAD THE HELPERS */
            $this->load->helper(array('url','html'));
            
        /* LOAD THE DATABASE FUNCTIONS */
            $this->load->database();
            $this->load->model('homesmodel');
        }
        
        public function index() {
            $this->load->view('view_homes');//THE VIEW CONTAINING THE TABLE TO BE FLEXED
        }
        
        function flex() {//THE PUBLIC FUNCTION TO PRINT THE TABLE CONTENTS
            if( ! $this->input->post('page')) {
                echo "You shouldn't be here";
                // redirect('homes');
            }
            else {
            $json =  $this->_populateFlexigrid();
            
            //THE JSON ENCODED DATA
            echo $json;
            }
        }
        
        
        function _populateFlexigrid() {
            
            header("Content-type: text/x-json");    
            
            /* GET THE POST */
            $page = $this->input->post('page');
            $rowsPerPage = $this->input->post('rp');
            $sortname = $this->input->post('sortname');
            $sortorder = $this->input->post('sortorder');
            $query = $this->input->post('query');
            $qtype = $this->input->post('qtype');
            
            /* CHECK THE POST */
                $sortname = ($sortname ? $sortname :  'id');//default sort
                $sortorder = ($sortorder ? $sortorder : 'desc');//default order
                $page = ($page ? intval($page) : 1);
                $rowsPerPage = ($rowsPerPage ? intval($rowsPerPage) : 10);
                $query = ($query ? $query : null);
                $qtype = ($qtype ? $qtype : null);
                $start = (($page-1) * $rowsPerPage);
    
            /* GET THE RECORDS BASED ON THE ARGUMENTS */
            $items = $this->homesmodel->fetch_homes($sortname,$sortorder,$rowsPerPage,$start,$query,$qtype);
                $homes = $items['homes'];
                $total = $items['total'];
                
            /* THE ARRAY TO BE ENCODED WITH KNOWN VARIABLES*/
            $json = array('page'=>$page, 'total'=>$total);
            
            foreach ($homes->result() AS $home) {
                
                /* ADD AN ICON FOR THE POOL RESULT */
                $pool = ($home->pool ? img('images/true.png') : '');
                
                $json['rows'][] = array(
                            'id'=>$home->id,
                            'cell' => array($home->id,$home->description,"$ ".number_format($home->price,0),number_format($home->sqft,0),$home->bedrooms,$pool),
                        ); 
            }
            return json_encode($json);
        }
        
    }
  • #338 / May 21, 2008 6:08am

    Synergiq

    12 posts

    Hi, is it possible to add some sort of styling to a certain row on the flexigrid dynamically? I would like to change the background color of rows that have a certain value.

  • #339 / May 21, 2008 6:09am

    wow thanks to Paulo’s excellent work - implementing a singleSelect was so easy. if anyone is interested reply and i’ll post the code here.

    regards
    Sean

    ReplyReply 🐍

    Indeed the Flexigrid is cool and Paulo did an excelent work. I have a solution for my problems, but it is not sophisticated. I am something like new at Javascript/DOM (usually I work with J2EE or PHP), but it is fascinating and sometimes strange and mindbogglingly :coolsmirk:.
    So it would be nice to see an implementation with events!


    Holla

  • #340 / May 21, 2008 10:22am

    grantmx

    1439 posts

    BTW Great thread guys…Paulo this would be good stuff to start a Wiki or Google Group with.

    Is there any way to skip the PHP echo or ASP call which then converts it to XML and instead just pull a hard XML file outputted from an already established db?

    Thanks!

  • #341 / May 21, 2008 11:07am

    coder1

    1 posts

    Since this thread is getting so long, would the flexigrid Google code project at http://code.google.com/p/flexigrid/ be a better place to post bug reports and possibly submit patches.  Is that the future home of flexigrid?  Hosting the downloads there would probably really help out on bandwidth issues.

    Thanks for the great component!

  • #342 / May 21, 2008 11:15am

    SeanRock

    4 posts

    wow thanks to Paulo’s excellent work - implementing a singleSelect was so easy. if anyone is interested reply and i’ll post the code here.

    regards
    Sean

    ReplyReply 🐍

    Indeed the Flexigrid is cool and Paulo did an excelent work. I have a solution for my problems, but it is not sophisticated. I am something like new at Javascript/DOM (usually I work with J2EE or PHP), but it is fascinating and sometimes strange and mindbogglingly :coolsmirk:.
    So it would be nice to see an implementation with events!


    Holla

    First let me make it clear i’m not a javascript or jquery expert. i’ve only been using jquery for a few days and flexigrid even less. So, this may not be ‘correct’ or the best way but it works for me.

    To add a onRowSelected event:

    1. open flexigrid.js and go to line (approx 52 - bottom of the options) and add the following (dont forget to add a comma after the previous option). I’ve included the onSubmit to show you where.

    .
    .
    .
    onSubmit: false, // using a custom populate function
    onRowSelected: false


    2. go to approx line 710. this is where jquery attaches the click event to the row. look for the line

    $(this).toggleClass('trSelected');

    and add the following code below it:

    // get the row id (unique id for the row)
    var selId = this.id.substring(3);
    
    // multiselect option here
    
    // if an event handler is defined then call it - only call if selecting, not unselecting
    if (p.onRowSelected && $(this).hasClass('trSelected'))
    {
        p.onRowSelected(selId,$(this),$(this).parent().parent().parent());
    }

    3. Add a new option to your flexigrid jquery code that will defined an event handler for the onRowSelected:

    $(document).ready(function()
    {
        $('.flexme').flexigird({onRowSelected:RowSelected});
    });

    and finally add your event handler to your page

    function RowSelected(id, row, grid)
    {
        alert("row id is " + id);
    }

    If you run this as-is the id will be empty. If you use dynamic data this will have a value but for static data (i.e. a table with rows and columns without dynamic data) you will need to add an id attribute to each row. example

    <tr id="row1">
        <td>cell 1</td>
    </tr>
    <tr id="row2">
        <td>cell 2</td>
    </tr>

    To allow only one selected row:

    1. open flexigrid.js and scroll to the bottom of the options (approx line 53). If you added the onRowSelected event above then below that you can add the following:

    onRowSelected: false;
    multiSelect: false // default to false

    2. again if you did the onRowSelected part then remember the comment that was added: // multiselect option here. go to this part and added the following code. its a bit long but easy to read.

    If you did not add the code for the onRowSelected then you will need to add the following before the next code block.

    // get the row id (unique id for the row)
    var selId = this.id.substring(3);
    // if multiSelect:false - loop over all rows and remove the trSelected class from other rows                                
    if(!p.multiSelect)
    {
        $('tbody tr', g.bDiv).each
        (
            function()
            {
                var thisId = this.id.substring(3);
                if(selId == thisId) // id is the currently selected row
                    return;
                else
                    $(this).removeClass('trSelected');
            }
        );
    }

    I borrowed most of this code from the method right above (thanks Paulo). It simply loops over all the rows and if it finds one that has the trSelected class then it removes it.

    3. as the default is false, i.e. only single row selection is allowed, if you want to allow multiple rows to be selected you can add the option like so:

    $(document).ready(function()
    {
        $('#flexme').flexigrid({multiSelect:true});
    });

    The same rule about the id attribute of the <tr> applies on single row select. Without the id single select does not work.

    Again i’m not an expert but it works.

    Regards
    Sean

  • #343 / May 21, 2008 11:57am

    Hey Sean,

    thanks for ur reply! I made it in nearly the same way, except the thing with the “event handler”. Good way.

    To go around the long slope to clear all trSelected I use this ‘oneliner’:

    $('#'+ t.id +' > tbody > .' + 'trSelected').removeClass('trSelected');

    But as far as I can see, I am not a Javascript prof 😊

    I try to use Flexigrid in very special project that doesn’t cry really for such a advanced application (a lot of database tables depending on each other). But I see it as a “skill enhancement” and I am able to spend some time with this brand new things (javascript, jquery, flexigrid). And I am still impressed, all this enhanced clientworking… The return of the fat-client, cool. I do not expect it in a browser, but it is really fun. 

    When it is all done I can buy Paulo a Coffee on my company’s bill 😝


    Holla

  • #344 / May 22, 2008 8:16am

    paky

    13 posts

    With [query] and [qtype] parameter ... can send to Json any data for personal search/filter in flexgrid ? Don’t exist another parameter for send to Json dynamic data ... ?

    Thanks all

  • #345 / May 22, 2008 8:29am

    paky

    13 posts

    2. Yes. There is an onSubmit API where you can add a Javascript that you can use to add a data using jQuery’s .serializeArray method. you can even return false to the API if you want to verify your user’s entered data, and prevent flexigrid from submitting to the server.

    ehm ... a small example 😊 thanks


    In my case I send to page a POST variables(array) ... can manipulate it ?

    thanks

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases