Skip to content
Derek Jones edited this page Jul 5, 2012 · 4 revisions

Develop a simple scaffolding for CRUD operations on tables. It works this way: Suppose you want to edit a master table:

/*
-----
users
----
id
category_id
name

---
*/

and want that your crud appears related to:

/*
----
category
----
id
name
*/

then this library is sufficient that you create a controller and configured as you want to see your crud.

could be:

Example class users

/system/controllers/users.php

<?php

class users extends Controller {

    public function __construct() 
    {
        parent::Controller();
        
        $param = array('baseclass'     =>__CLASS__,
                'table'        =>'users',
                'slaves'=>array(
          array('table'=>
                    array(
                'name'        =>'category',
                'caption'    =>'name'    ,
                'id'        =>'id'    ,
                'join'        =>'category_id'
                )
            )
            ),
                'hidden'=>array('id'),
                 'rename'=>array(
                        'User Category'=>'category_id',
                                                'User Name'    =>'name'
                         )
                       );
        
        $this->load->library('libscaffolding',$param);
    }
    

    function index()
    {
        echo "<p>".$this->libscaffolding->newlink()."</p>";
        echo "<p>".$this->libscaffolding->all()."</p>";
    }
    
    public function edit($id)
    {
        echo "<p>".$this->libscaffolding->edit($id)."</p>";
    }
    
    public function view($id)
    {
        echo "<p>".$this->libscaffolding->view($id)."</p>";
    }
        
    public function delete($id)
    {
        $this->libscaffolding->_delete($id);
    }
    
    public function update($id)
    {
        $this->libscaffolding->_update($id,$_POST);//do better
    }
    
    public function add()
    {
        echo "<p>".$this->libscaffolding->add()."</p>";
    }
    
    public function insert()
    {
        $this->libscaffolding->_insert($_POST);//do better
    }

}
?&gt;

clever! crud you already have a warm relationship with which you can customize to your liking.

to install this feature you must: install the following file:

/system/libraries/libscaffolding.php

&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Scaffolding library for Code Igniter applications
 * Author: Daniel Romero, Jaguarcode Consulting, www.jaguarcode.com.ar, February 2009
 */


class libscaffolding {
    
    
    private $base;
    private $table;
    private $slaves;
    private $hidden     = array(); //columns to hidden ->egg optional
    private $redir      = 'yes';   //redir to main view ->egg optional
    private $rename     = array(); //rename main columns ->egg optional
    private $sql        = false;   //change a table by a complex sql statement ->egg optional
    private $showpanel    = true;    //show control panel for all method ->egg optional
    private $styletable    = false;   //show style for control panel ->egg optional
    
    private $table_select;
    private $slave_select;
    
    /**
     * ::construct(array)
     *     
     *    array::struct
     *    |
     *    |-> table         :: master table for crud
     *    |-> baseclass     :: class trigger 
     *    |-> slaves         :: array with joined tables
     *        |
     *        |->name        :: join table name
     *        |->caption    :: field for reemplaze
     *        |->id        :: field id
     *        |->join        :: field for equalizer     
     *
     */
    public function __construct($config)
    {
        if (!isset($this->CI)) $this->CI =& get_instance();
        
        $this->CI->load->model  ('advanced','',TRUE);
        $this->CI->load->library('table');
        
        $this->table  = $config["table"];
        $this->slaves = $config["slaves"];
        $this->base      =    base_url().$config["baseclass"];
        
        if(is_array    ($config["hidden"    ]    ))    $this->hidden         = $config["hidden"        ];
        if(isset    ($config["redirect"    ]    ))    $this->redir          = $config["redirect"    ];
        if(isset    ($config["rename"    ]    ))    $this->rename         = $config["rename"        ];
        if(isset    ($config["statement"]    ))    $this->sql             = $config["statement"    ];
        if(isset    ($config["showpanel"]    ))    $this->showpanel     = $config["showpanel"    ];
        if(isset    ($config["styletable"]    ))     $this->styletable     = $config["styletable"    ];    
        
        $this->setstyle();
        
    }


    private function setstyle()
    {
        if($this->styletable!=false)
        {
            $this->CI->table->set_template($this->styletable);
        }
    }

    /**
     * ::select 
     *    
     *    |->select all for all tables
     *
     */
    private function select()
    {
        $this->table_select =  $this->mainget();//$this->CI->advanced->get($this->table);
        
        $this->slave_select = array();
        
        foreach($this->slaves as $rows)
        {
            $this->slave_select[$rows['table']['name']] =  $this->CI->advanced->get($rows['table']['name']);
        }
    }
    
    private function mainget()
    {
        $rs = "";

        if($this->sql==false)
            $rs = $this->CI->advanced->get($this->table);
        else
            $rs = $this->CI->advanced->query($this->sql);
        
        return $rs;
    } 
    
    
    /**
     * ::all 
     *    
     *    |->Generate master view 
     *        |->Return html
     *
     */
    public function all()
    {
        $this->select();
        
           if ($this->table_select->num_rows() == 0) 
               {
                  die('<p>The table appears to have no data.</p>');
             } 
            else 
            {
                $this->CI->table->set_heading($this->getfield());
                
                foreach ($this->table_select->result() as $row) 
                {
                    $tmp_row=array();
                    
                    foreach($row as $key=>$value)
                    {
                        foreach($this->slaves as $slave)
                        {
                            $slave_table     = $slave['table']['name'    ]; //empresas
                            $slave_caption     = $slave['table']['caption'    ]; //nombre
                            $slave_id         = $slave['table']['id'        ]; //codigo
                            $slave_join     = $slave['table']['join'    ]; //id_empresa
                            
                            $rw = $this->slave_select[$slave_table];
                            
                            $value = $this->getvalue(array(
                                                           'slave_join'        =>$slave_join    ,
                                                           'slave_caption'    =>$slave_caption,
                                                           'slave_id'        =>$slave_id        ,
                                                           'key'            =>$key            ,
                                                           'rw'                =>$rw            ,
                                                           'value'            =>$value
                                                           ));
                        }
                        
                        if(in_array($key,$this->hidden))
                        {}
                        else
                        $tmp_row[]= $value;
                    }
                    
                    if($this->showpanel)
                    $tmp_row[]= "    
                                    <a >base}/view/{$row->id}' class='view'>View</a>
                                    <a >base}/edit/{$row->id}' class='edit'>Edit</a> 
                                     <a >base}/delete/{$row->id}' class='delete'>delete</a>
                                    
                                ";
                    
                    
                    $this->CI->table->add_row($tmp_row);
                }
            }
        
        return $this->CI->table->generate();
         
    }
    
    private function getfield()
    {
        $fields  = $this->table_select->field_data();
        
        $headers = array();
        
        foreach ($fields as $field) 
        {

            if(in_array($field->name,$this->hidden))
            {}
            else
            {
                    $key_found = array_search($field->name,$this->rename);
                    
                    if($key_found) 
                    $headers []= "<strong>$key_found</strong>";
                    else
                    $headers []= "<strong>$field->name</strong>";
                
            }
        }
        $headers []="&nbsp;";    
        
        return $headers;
    }
    
    private function getvalue($array)
    {
        if( $array['slave_join'] == $array['key'] )
            foreach ($array['rw']->result() as $rs) 
            {
                $keyfound = false;
                
                foreach( $rs as $k=>$v )
                {
                    if( $array['slave_id'] == $k ) 
                        if( $array['value'] == $v  ) 
                            $keyfound = true;
                    
                    if( $array['slave_caption'] == $k ) 
                        if( $keyfound == true) 
                            $array['value'] = $v;
                }
                
            }
            
        return $array['value'];
    }
    
    /**
     * ::view 
     *    
     *    |->Generate master view table
     *        |->Return html
     *
     */    
    public function view($id)
    {
        
        $this->select();
        
        if ($this->table_select->num_rows() == 0) 
               {
                  echo '<p>The table appears to have no data.</p>';
             } 
            else 
            {
                foreach ($this->table_select->result() as $row) 
                {
                    if((int)$row->id == (int)$id)
                    {
                        foreach($row as $key=>$value)
                        {    
                            foreach($this->slaves as $slave)
                            {
                                $slave_table     = $slave['table']['name'    ]; //empresas
                                $slave_caption     = $slave['table']['caption'    ]; //nombre
                                $slave_id         = $slave['table']['id'        ]; //codigo
                                $slave_join     = $slave['table']['join'    ]; //id_empresa
                                
                                $rw = $this->slave_select[$slave_table];
                                
                                $value = $this->getvalue(array(
                                                           'slave_join'        =>$slave_join    ,
                                                           'slave_caption'    =>$slave_caption,
                                                           'slave_id'        =>$slave_id        ,
                                                           'key'            =>$key            ,
                                                           'rw'                =>$rw            ,
                                                           'value'            =>$value
                                                           ));
                                
                            }
                            
                            if(in_array($key,$this->hidden))
                            {}//
                            else
                            {
                                $key_found = array_search($key,$this->rename);
                                if($key_found) 
                                    $key = $key_found;
                                
                                
                                $this->CI->table->add_row(array("<strong>$key</strong>",$value));
                            
                            }
                        }
                    }

                }
            }
            
            return $this->CI->table->generate();
    }
    
    
    
    /**
     * ::edit 
     *    
     *    |->Generate master form
     *        |->Return html
     *
     */        
    public function edit($id)
    {
        
        $this->select();
        
        if ($this->table_select->num_rows() == 0) 
               {
                  echo '<p>The table appears to have no data.</p>';
             } 
            else 
            {
                foreach ($this->table_select->result() as $row) 
                {

                    if((int)$row->id == (int)$id)
                    {
                        foreach($row as $key=>$value)
                        {    
                            $input =  "&lt;input type='text' name='$key' value='$value' /&gt;";
                        
                            foreach($this->slaves as $slave)
                            {
                                $slave_table     = $slave['table']['name'    ]; //empresas
                                $slave_caption     = $slave['table']['caption'    ]; //nombre
                                $slave_id         = $slave['table']['id'        ]; //codigo
                                $slave_join     = $slave['table']['join'    ]; //id_empresa
                                
                                $rw = $this->slave_select[$slave_table];
                                
                                if( $slave_join == $key )
                                    $input = $this->dropdown(array(
                                                                   'slave_join'        =>$slave_join    ,
                                                                   'slave_caption'    =>$slave_caption,
                                                                   'slave_id'        =>$slave_id        ,
                                                                   'key'            =>$key            ,
                                                                   'rw'                =>$rw            ,
                                                                   'value'            =>$value
                                                                   ));
                            }
                            
                            if(in_array($key,$this->hidden))
                            {}//
                            else
                            {
                                $key_found = array_search($key,$this->rename);
                                if($key_found) 
                                    $key = $key_found;
                                
                                
                                $this->CI->table->add_row(array("<strong>$key</strong>",$input));
                            
                            }
                            
                            
                        }
                        
                        $this->CI->table->add_row(array(" ","&lt;input type='submit' name='btn' value='Update'&gt;"));
                    }

                }
            }
            
            return "&lt;form action='{$this-&gt;base}/update/{$id}' method='post'>".$this->CI->table->generate()."&lt;/form&gt;";
    }
    
    private function dropdown($array)
    {
        $input ="<select name='".$array['key']."'>";
        
        foreach ($array['rw']->result_array() as $rs) 
        {
            $keyfound = false;
            $selected = "";
            
            if($rs[$array['slave_id']]==$array['value']) $selected="selected='selected'";
            
            $input.="<option value='".$rs[$array['slave_id']]."' $selected>".$rs[$array['slave_caption']]."</option>";
        }
        
        $input.="</select>";
        
        
        return $input;
    }
    
    /**
     * ::_delete 
     *    
     *    |->Delete selected element
     *        |->Redirect
     *
     */        
    public function _delete($id)
    {
        $this->CI->advanced->delete(array('table'=>$this->table,'field'=>'id','value'=>$id));
        $this->transfer();
    }
    
    /**
     * ::_update 
     *    
     *    |->Update selected element
     *        |->Redirect
     *
     */            
    public function _update($id,$array)
    {
        unset($array['id']);
        unset($array['btn']);
        $array['id'] = $id;
        
        $this->CI->advanced->update(array(
                                          'table'    =>$this->table,
                                          'field'    =>'id',
                                          'id'        =>$array['id'],
                                          'data'    =>$array
                                          ));
        $this->transfer();
    }
    

    
    /**
     * ::_insert 
     *    
     *    |->Insert selected element
     *        |->Redirect
     *
     */    
    public function _insert($array)
    {
        unset($array['id']);
        unset($array['btn']);
        
        $array['id'] = $this->CI->advanced->max($this->table,'id')+1;
        
        $this->CI->advanced->insert(array(
                                          'table'    =>$this->table,
                                          'data'    =>$array
                                          ));
        $this->transfer();
    }
    
    /**
     * ::newlink 
     *    
     *    |->Get link for insert
     *        |->return html
     *
     */        
    public function newlink()
    {
        return "<a >base}/add/'>new</a>";
    }
    
    private function transfer()
    {
        if($this->redir =='yes')
            redirect($this->base);    
    }

    /**
     * ::add 
     *    
     *    |->Generate insert form
     *        |->return html
     *
     */            
    public function add()
    {
        $id=1;$b=false;
        $this->select();
        
        if ($this->table_select->num_rows() == 0) 
               {
                  echo '<p>The table appears to have no data.</p>';
             } 
            else 
            {
                foreach ($this->table_select->result() as $row) 
                {

                    if($b==false)
                    {
                        foreach($row as $key=>$value)
                        {    
                            $input =  "&lt;input type='text' name='$key' value='' /&gt;";
                        
                            foreach($this->slaves as $slave)
                            {
                                $slave_table     = $slave['table']['name'    ]; //empresas
                                $slave_caption     = $slave['table']['caption'    ]; //nombre
                                $slave_id         = $slave['table']['id'        ]; //codigo
                                $slave_join     = $slave['table']['join'    ]; //id_empresa
                                
                                $rw = $this->slave_select[$slave_table];
                                
                                if( $slave_join == $key )
                                    $input = $this->dropdown(array(
                                                                   'slave_join'        =>$slave_join    ,
                                                                   'slave_caption'    =>$slave_caption,
                                                                   'slave_id'        =>$slave_id        ,
                                                                   'key'            =>$key            ,
                                                                   'rw'                =>$rw            ,
                                                                   'value'            =>0
                                                                   ));
                            }//endforeach
                            
                            if(in_array($key,$this->hidden))
                            {}//
                            else
                            {
                                $key_found = array_search($key,$this->rename);
                                if($key_found) 
                                    $key = $key_found;
                                
                                
                                $this->CI->table->add_row(array("<strong>$key</strong>",$input));
                            
                            }
                            
                            
                        }//endforeach
                        
                        $this->CI->table->add_row(array(" ","&lt;input type='submit' name='btn' value='Insert'&gt;"));
                    }//endif
                    $b=true;

                }
            }
            
    return "&lt;form action='{$this-&gt;base}/insert/' method='post'>".$this->CI->table->generate()."&lt;/form&gt;";
    }
    
}
?&gt;

You must install this model /system/models/advanced.php

&lt;?php

class advanced extends Model 
{
    public function __construct() 
    { 
        parent::Model();
    }
    
    public function get($tabla) 
    {   
         return $this->db->get($tabla);
    }
    
    public function query($string)
    {
        return $this->db->query($string);
    }
    
    public function delete($array) 
    {   
         $this->db->delete($array['table'], array($array['field'] => $array['value'])); 
    }
    
    public function update($array) 
    {   
         $this->db->where($array['field'], $array['id']);
        $this->db->update($array['table'], $array['data']); 
    }
    
    public function insert($array){
        
        $this->db->insert($array['table'], $array['data']);     
    }
    
    public function max($table,$field)
    {
        $max ="";
        
        $this->db->select_max($field);
        $rs =$this->db->get($table);
        
        foreach($rs->result_array() as $row)
        {
            $max = $row[$field];
        }
        
        return $max;
    }
    
}
?&gt;

presto, the library has more functions to better use, you can fit your needs bye!

Clone this wiki locally