Jump to content

Most Liked Content

#4286 [updated 24/11/2012] Dependent dropdown (library)

Posted victor on 16 November 2012 - 03:35 PM

Hi all! This is my second library.
If you have a few dependent dropdowns on any page this library for you.
When you made selection in a "Parent" dropdown the library refreshes a "child" dropdown.

Advantage of this library:

  • integration is easily
  • it is not required to change a template
  • it is not required to create a callback function

The library works perfectly with GC v 1.5.x and CI 3.x

Download here:

v 1.5.1 Attached File  Gc_dependent_select.php   11.36K   1273 downloads


v 1.2.0 Attached File  gc_dependent_select.php   9.14K   4567 downloads
v 1.1.1 Attached File  gc_dependent_select.php   6.64K   977 downloads
v 1.1.0 Attached File  gc_dependent_select.php   6.34K   884 downloads
The library v.1.1.0 has a bug!

How to use (v. 1.2.0.):

$crud = new grocery_CRUD();
$crud->set_relation('goods_country', 'dd_country', 'country_title');
$crud->set_relation('goods_state', 'dd_state', 'state_title');
$crud->set_relation('goods_city', 'dd_city', 'city_title');

// settings

$fields = array(

// first field:
'goods_country' => array( // first dropdown name
'table_name' => 'dd_country', // table of country
'title' => 'country_title', // country title
'relate' => null // the first dropdown hasn't a relation
// second field
'goods_state' => array( // second dropdown name
'table_name' => 'dd_state', // table of state
'title' => 'state_title', // state title
'id_field' => 'state_id', // table of state: primary key
'relate' => 'country_ids', // table of state:
'data-placeholder' => 'select state' //dropdown's data-placeholder:

// third field. same settings
'goods_city' => array(
'table_name' => 'dd_city',
'where' =>"post_code>'167'",  // string. It's an optional parameter.
'order_by'=>"state_title DESC",  // string. It's an optional parameter.
'title' => 'id: {city_id} / city : {city_title}',  // now you can use this format )))
'id_field' => 'city_id',
'relate' => 'state_ids',
'data-placeholder' => 'select city'

$config = array(
'main_table' => 'dd_goods',
'main_table_primary' => 'goods_id',
"url" => base_url() . __CLASS__ . '/' . __FUNCTION__ . '/', path to method
'ajax_loader' => base_url() . 'ajax-loader.gif' // path to ajax-loader image. It's an optional parameter
'segment_name' =>'Your_segment_name' // It's an optional parameter. by default "get_items"
$categories = new gc_dependent_select($crud, $fields, $config);

// first method:
//$output = $categories->render();

// the second method:
$js = $categories->get_js();
$output = $crud->render();
$output->output.= $js;


You can't use the callback_edit_field and callback_add_field for this field. You can use callback_edit_field and callback_add_field only for the first field

example 2:

function test()
$crud = new grocery_CRUD();
$crud->set_relation('category_id', 'category', 'category_name');
$crud->set_relation('subcategory_id', 'sub_category', 'subcategory_name');
$crud->set_relation('zone_id', 'zone', 'zone_name');
$crud->set_relation('subzone_id', 'sub_zone', 'subzone_name');

$fields = array(
'category_id' => array(// first dropdown name
'table_name' => 'category', // table of country
'title' => 'country_title', // country title
'relate' => null // the first dropdown hasn't a relation
'subcategory_id' => array(// second dropdown name
'table_name' => 'sub_category', // table of state
'title' => 'subcategory_name', // state title
'id_field' => 'id', // table of state: primary key
'relate' => 'category_id', // table of state:
'data-placeholder' => 'Select Subcategory' //dropdown's data-placeholder:
$config = array(
'main_table' => 'dd_goods',
'main_table_primary' => 'goods_id',
"url" => base_url() . __CLASS__ . '/' . __FUNCTION__ . '/',
$categories = new gc_dependent_select($crud, $fields, $config);
$js = $categories->get_js();

$fields2 = array(
'zone_id' => array(// first dropdown name
'table_name' => 'zone', // table of country
'title' => 'country_title', // country title
'relate' => null // the first dropdown hasn't a relation
'subzone_id' => array(// second dropdown name
'table_name' => 'sub_zone', // table of state
'title' => 'subzone_name', // state title
'id_field' => 'id', // table of state: primary key
'relate' => 'zone_id', // table of state:
'data-placeholder' => 'Select Subzone' //dropdown's data-placeholder:
// change the "segment_name"!!!
$config2 = array(
'main_table' => 'dd_goods',
'main_table_primary' => 'goods_id',
"url" => base_url() . __CLASS__ . '/' . __FUNCTION__ . '/',
'segment_name' => "other_name"
$categories2 = new gc_dependent_select($crud, $fields2, $config2);
$js2 = $categories2->get_js();

$output = $crud->render();
$output->output.= $js . $js2;


P.S. Thanks to web-johnny, thanks to KaBaDaBrA and to me http://www.grocerycr..._DIR#/smile.png .
P.S.S. Code can contain some bugs . If you find a bug - report, please.
Sorry, my English is poor.

#7285 Remember to use the CodeIgniter and Grocery CRUD manuals

Posted davidoster on 09 May 2013 - 11:20 AM

Dear all,


as you know the current stable version of Grocery CRUD utilizes the wonderfull (and super fast) CodeIgniter framework.

This means that the code is based on this and hence it is good to know a few things about this framework before we start using it.


Many questions can be answered just by looking to the manual,



and the Grocery CRUD's manual also.


Following victor's suggestion we include some additional information that might be useful to you.


1. Read these tutorials on how to use the developer tools of your browser

- for Internet Explorer, http://msdn.microsof...7(v=vs.85).aspx

- for FireFox, http://www.howtogeek...eveloper-tools/

- for Google Chrome, https://developers.g...eveloper-tools/

(feel free to suggest more tutorials!  :D )


2. Use, during development, PHP's error reporting,


Edited by web-johnny
Also please make sure the the display_errors is set to "On" in your php.ini file (suggested).

display_errors = On

or in your php index.php file add:

ini_set('display_errors', 'On');
3. Learn all about CodeIgniter's error handling here: 
4. Are you sure that you are using the latest stable version of grocery CRUD? Did you know that the latest code on github is under development and it is not suggested to be used to production mode? Edited by web-johnny
5. Remember to smile  :) . All the support of the forum is for free and people try to help, so keep that in mind and please respect any given answer. Edited by web-johnny


Thank you! Keep on supporting this great software!

#6865 Filter relation using third table

Posted davidoster on 15 April 2013 - 09:19 PM

To be honest I find it easier to build a new model and just say,

/* sample code */

//mymodel.php under application/models
class mymodel extends CI_Model  {
	function __construct()

        public function get_activities_by_year($table, $year)
		$this->db->select('id, year, description');
		$this->db->where('year', $year);
                $this->db->order_by('id desc');
		return $this->db->get($table);


$activities = $this->mymodel->get_activities_by_year("activities","2013");
foreach ($activities->result() as $row)
 $myarray[$row->id] .= $row->description;

#4308 [updated 24/11/2012] Dependent dropdown (library)

Posted web-johnny on 18 November 2012 - 10:51 AM

Hello victor,

your library seems really cool. By the way I changed your Member title to "grocery CRUD Hero" . I hope you like it :D

#1458 [ANSWERED] set_relation and "Add New" button to quick insert.

Posted KaBaDaBrA on 25 April 2012 - 06:08 PM

Aloha!! :D

K well I think I know what you might want - so might have a solution for you. I quickly helped some other guys with a fancybox question, here's how you can do something similar:

1. Download Fancybox: http://fancyapps.com/fancybox/

2. Add this code to the view file (You'll have to change a few of the paths and names etc)

<link rel="stylesheet" href="<?=base_url()?>assets/plugins/fancybox/jquery.fancybox.css?v=2.0.6" type="text/css" media="screen" />
<script type="text/javascript" src="<?=base_url()?>assets/plugins/fancybox/jquery.fancybox.pack.js?v=2.0.6"></script>
<script type="text/javascript">
$(document).ready(function() {

$('#countryID_input_box').append('<a href="<?=site_url()?>/examples/quick_add/" class="various fancybox.ajax">Add</a>');

3. Add this code to you controller (Again you will have to make modifications to work with your own code)

function quick_add()
  $args = array(
'category_name' => 'select[name="countryID"]'

  $javascript = '
  function do_quick_add()
var category_text = $(\'#category_item\').val();
var category_id = $(\''.$args['category_name'].'\').val();

$.post(\''.site_url().'/examples/quick_add_save/\', { categoryID: category_id, category_item: category_text }, function(data) {
$(\''.$args['category_name'].'\').prepend(\'<option value="\'+data+\'">\'+category_text+\'</option>\');
$(\'#category_message\').html(\'Successfully inserted a new category\');

  $html = '
  <div style="width: 400px; height: 250px;">
  <div style="padding: 5px;">New Category Name:</div>
  <div style="padding: 5px;"><input type="text" name="category_item" id="category_item"></div>
  <div style="padding: 5px;"><input type="button" value="Add &raquo;" onclick="do_quick_add();"> <span id="category_message"></span></div>

  echo $javascript.$html;

function quick_add_save()
$categoryID = $this->input->post('categoryID', true); //only needed if adding a sub category, can get parent ID
$category_text = $this->input->post('category_item', true);

$data = array(
'country_title' => $category_text
$this->db->insert('country', $data);

return $this->db->insert_id();

VOILA!!!! :)

Add to select.PNG

Now you can quickly add to dropdowns without having to leave the page.

If it's not exactly what you want you can use a similar approach by using jquery to modify things...

#9795 PDF version of GroceryCRUD 2.1.4 API and Function list

Posted edramirez on 20 October 2013 - 11:17 PM

Here is a PDF version of the GroceryCRUD for those who may have to develop applications offline.Attached File  grocerycrud API and Functions list.pdf   425.6K   3215 downloads

#9547 How to use Invisible field

Posted davidoster on 21 September 2013 - 10:24 PM

As we grow old we get wiser!

So, in that sense I wanted to point out the use of the invisible field.

When we make for example a callback_before_insert (as the above example code states) we might need to exclude some fields from the add form but still want to pass some value to these fields that will be stored on the database.


The solution to this is actually quite simple.

We just use the fields function to state all of the fields that will take part on the insert process and this means also the fields that should not be showing up.

Then in order to "hide" the unwanted fields, hence the ones we want not to be displayed at the form and by hand pass them some value we mask them with the use of the field_type function with the use of the invisible type.

This gets quite handy and easy to use when we want for example to insert some extra data about the record that is saved on the database.

For example when we want to save the date/time of insertion, or if we need to know the user that inserted this record, or if we want to encrypt some sort of information like a password. The possibilites are just endless and the mecanism is there to help us out, straight out of the box!

#7615 Drag and drop for order of items

Posted Amit Shah on 23 May 2013 - 02:48 PM

Well as promised,


I have applied the library to the latest build of the grocery crud (pulled from svn).


You guys can find the implemented example code for the following at https://github.com/b..._with_drag_drop


Well i should really thanks the team up here who have provided me an opportunity to improve my code. Earlier, i ran through with a certain set of assumption that everyone (like i used to do) would be using up id as primary key. I know i was wrong to assume that and had improvised the code over while implementing it with the example on the grocerycruds pre-provided example (products manager)

So i am also attaching the fresh code here along with this post.


Hope guys can take the advantage of the application / library to the max.

Attached Files

#6059 How to pass extra data on a grocery crud view

Posted silva96 on 27 February 2013 - 02:31 PM

I would suggest what I do always with views, Use a template with header, content, footer. (after the theory I'll explain how to use it with grocery crud)


first: The template: (template.php)




With this, we have a standard template.


To load a view, use this code:


class Users enxtends CI_Controller {
//any controller...
  public function login(){ //any function...


This way, you are loading a view within a template, passing extra data to the template (second parameter $data).


With this logic, you don't need to change grocery-crud's core, try this instead:


Header: include crud's styles and javascripts. (includes/header.php)


      foreach($css_files as $style){
          echo '<link href="'.$style.'" rel="stylesheet"/>';
      foreach($js_files as $script){
          echo '<script src="'.$script.'" type="text/javascript"></script>';


crud_content_view: echo the output (crud_content_view.php)


<?php echo $output;?>


Controller/function (crud_controller.php)


$output=$crud->render(); //$output is an object with attributes: js_files,css_files,output
$output->content_view='crud_content_view'; //we add a new attribute called content_view
//because our template loads the view content_view for the content.
//if we want to pass data, try this.
//etc, then assign data to output.


Then to access data in the view try this: (in crud_content_view.php)


echo $data['variable1'];
echo $data['variable2'];
foreach($data['variable3'] as $var3){
 echo $var3;


This is good practice from codeigniter's manual, try to not alter the crud library core.



#486 Right To Left Theme For RTL Languages

Posted Moslem Mansouri on 11 February 2012 - 02:34 PM

Hello to all

Right to left style for RTL languages :

Updated to version 1.3.2
Please download a new file Attached File  RTL.zip   10.64K   1140 downloads

1 - Please download Attached File  RTL.zip   10.64K   1140 downloads
2  - Extract to "assets\grocery_crud\themes"
3  - Confirm And Replace File And Folder
Good Luck
Admin please add the package to all your friends to enjoy
ThankDear Admin

#2196 CI Modular Extensions - HMVC & Grocery_CRUD

Posted noskov on 07 June 2012 - 09:46 PM

This is a compilation of CodeIgniter, Modular Extentions - HMVC and lovely Grocery_CRUD. Maybe for someone it will be useful :)

First of all download CI and make a fresh instalation. No one likes /index.php/ in the urls, so we add for our project .htaccess file with these lines:
RewriteEngine on
RewriteCond $1 !^(index\.php|robots\.txt|assets)
RewriteRule ^(.*)$ /index.php/$1 [L]

and remove "index.php" from line #54 in our ./application/config/config.php file to have this instruction:
$config['index_page'] = '';


Now we are going to make our CI application modular. Download Modular Extentions - HMVC and put it's content (just "core" and "third_party" folders) to the corresponding CodeIgniters folders.

In the next step create ./application/modules/ folder. Then create ./application/modules/welcome/ folder and create in it ./applications/modules/welcome/controllers/ and ./applications/modules/welcome/views/ folders.

Then move ./application/controllers/welcome.php file to ./application/modules/welcome/controllers/welcome.php. And ./application/views/welcome_message.php file to ./application/modules/welcome/views/welcome_message.php (ughh, sorry for this :wacko:).

Go to the ./application/config/config.php file and add this line to say where our modules are located:
$config['modules_locations'] = array(APPPATH.'modules/' => '../modules/');

Now just change line#28 in welcome.php into this, so our contoller extends MX_Controller and not CI_Controller:
class Welcome extends MX_Controller {

After this, if we see in the browser favorite "Welcome to CodeIgniter!", then everythigs is OK and our CI is modular.


Now go to the grocery_CRUD and download it. Use examples_database.sql for creating your test db. Then put ./assets/ folder along with ./application/ and ./system/ CI-folders.

Create new ./application/modules/grocery_crud/ folder and put into it content of grocery_CRUD ./application/ folder to have structure like this:












Since we have HMVC our controllers have to extend MX_Controller. Go to the ./application/modules/grocery_crud/controllers/examples.php file and change line#3 into this:
class Examples extends MX_Controller {

I encoutered the problem: MX_Loader doesn't want to load library if it's name capitilize. So change and the line#11 into:

and add line#12:
to load the url_helper for our links.

Then go to the ./application/modules/grocery_crud/views/example.php file and change lines#31-36 into these:
<a href='<?php echo site_url('grocery_crud/examples/customers_management')?>'>Customers</a> |
<a href='<?php echo site_url('grocery_crud/examples/orders_management')?>'>Orders</a> |
<a href='<?php echo site_url('grocery_crud/examples/products_management')?>'>Products</a> |
<a href='<?php echo site_url('grocery_crud/examples/offices_management')?>'>Offices</a> |
<a href='<?php echo site_url('grocery_crud/examples/employees_management')?>'>Employees</a> |
<a href='<?php echo site_url('grocery_crud/examples/film_management')?>'>Films</a>

And the last thing: add ./application/modules/grocery_crud/config/routes.php file with this content:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$route['grocery_crud'] = 'examples';

/* End of file routes.php */
/* Location: ./application/modules/grocery_crud/config/routes.php */
in order to have routing to the examples controller, when we access your_project.com/grocery/

If you can browse your_project.com/grocery_crud and see the index of grocery everything is fine.

Result in .zip archive can be found in ci_hmvc_grocery_crud.

Additional documentation you can find in wiki & docs of CI, Modular Extentions - HMVC and grocery_CRUD.

#1945 Default field values (for add form)

Posted Fouzi on 24 May 2012 - 04:13 PM

We can use the default value saved in each field type, this modification require one line code modification

FILE: application/libraries/grocery_crud.php
protected function get_add_input_fields($field_values = null)
  $fields = $this->get_add_fields();
  $types  = $this->get_field_types();
  $input_fields = array();

  foreach($fields as $field_num => $field)
   $field_info = $types[$field->field_name];
// OLD //    $field_value = !empty($field_values) && isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : null;
/* NEW */  $field_value = !empty($field_values) && isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : $field_info->default;

and when creating your table in SQL, change DEFAULT NULL with DEFAULT your_value

CREATE TABLE `mytable` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(25) DEFAULT NULL,
  `longtext` varchar(255) DEFAULT NULL,
  `icon` varchar(255) DEFAULT NULL,
  `isenabled` tinyint(1) DEFAULT '1',
  PRIMARY KEY (`id`)
) ;

everytime you create a new record, the field 'isenabled' will have 1 (true) as a default value

This can be done also with Database Forge Class
What do you think?

#10354 Codeigniter 2 Cookbook

Posted web-johnny on 15 December 2013 - 02:27 PM

I am proud to announce the Codeigniter 2 Cookbook . I am one of the 4 official reviewers of the book :) . You can see my name at the credits :) :) :) http://packtlib.pack...y/9781782162308 (Go to credits)


I know that here is not facebook, but like this post if you are as happy as I am :)






#9747 Grocery Crud in laravel

Posted franzr on 12 October 2013 - 02:10 PM

Just made an account to say thank you


grocerycrud is the only thing that keeps me in CI

#9414 Bug in the search

Posted Amit Shah on 10 September 2013 - 07:41 AM

Hi team,


I was looking for this solution and finally found it... i was wanting to perform the search desperately but failing to do with the existing issue of GC. Hence i finally updated the function and made the relevant changes.

protected function set_ajax_list_queries($state_info = null)
            if(empty($state_info->page) || !is_numeric($state_info->page) )
                $limit_page = ( ($state_info->page-1) * $state_info->per_page );
                $this->limit($state_info->per_page, $limit_page);


                foreach($this->relation as $relation_name => $relation_values)
                    $temp_relation[$this->_unique_field_name($relation_name)] = $this->_get_field_names_to_search($relation_values);

            if($state_info->search->field !== null)
                        foreach($temp_relation[$state_info->search->field] as $search_field)
                            $this->or_like($search_field , $state_info->search->text);
                        $this->like($temp_relation[$state_info->search->field] , $state_info->search->text);
                    $escaped_text = $this->basic_model->escape_str($state_info->search->text);
                    $this->having($state_info->search->field." LIKE '%".$escaped_text."%'");
                    $this->like($state_info->search->field , $state_info->search->text);
                $columns = $this->get_columns();

                $search_text = $state_info->search->text;

                    foreach($this->where as $where)

                //Get the list of actual columns and then before adding it to search ..
                //compare it with the field ... does it exists? .. if yes.. great ..
                //go ahead and add it to search list.. if not.. just ignore it                
                $field_types = $this->get_field_types();
                $actual_columns = array();
                foreach($field_types as $field) {
                    if( !isset($field->db_extra) || $field->db_extra != 'auto_increment' )
                        $actual_columns[] = $field->name;
                foreach($columns as $column)
                            foreach($temp_relation[$column->field_name] as $search_field)
                                $this->or_like($search_field, $search_text);
                            $this->or_like($temp_relation[$column->field_name], $search_text);
                        //@todo have a where for the relation_n_n statement
                        if(array_search($column->field_name, $actual_columns) === false) {
                        $this->or_like($column->field_name, $search_text);

I have tested with Flexigrid.. (i by default use this single theme only) ... and it is functional / working smoothly - without much trouble on the same. Further improvements are surely invited. But as for now.. any1 who wants to make use of this newly modified functionality .. can surely take it to their advantage.


And David - have posted the same solution to the github too :)


Happy GCing...

#9222 File upload uniqueid not unique

Posted doritos on 27 August 2013 - 09:53 PM

When adding or editing a form with 2 or more file upload elements only the first one is uploaded, no matter wich of all upload button you press.


This happen when the form generate a duplicate uniqueid for inputs and buttons that are involved in selecting and uploading a file.


The problem is that library Grocery_CRUD.php,v1.3,function get_upload_file_input,about line 2531, try to generate a uniqueid

$unique = uniqid()


But, according to this post: http://stackoverflow.com/a/4070285 it sometimes happen that 2 or more uniqueid are generated in same second(windows) or microsecond(unix), and this causes the failure with the upload file buttons.


In my case I just changed line $unique = uniqid() by $unique = rand(10,9999) and problems with file upload dissapear...


I suggest using something else than uniqid() to avoid this kind of problems...








#8698 updated [30/07/2013] multiple uploading

Posted victor on 30 July 2013 - 07:52 PM

This is my 3-th topic for our community!  

Hello! I have not had any time for this forum. I was very busy, and I'm busy now too...

So,  I've made an example of multi-uploading because of a lot of people ask about it.

I didn't want to show this example before because of the example is difficult for newbies of GC and PHP and there will too much questions. 

This is result of my work:


NOTE: The example can contain any errors. But I won't change that because it's only example!!!

Are you ready?

Ok! Look at this code:


Database scheme

  `file_id` int(11) NOT NULL AUTO_INCREMENT,
  `file_name` text NOT NULL,
  `gallery_id` int(11) NOT NULL,
  PRIMARY KEY (`file_id`)

  `title` text NOT NULL,
  PRIMARY KEY (`id`)

PHP code:


if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Uploade extends CI_Controller {

    function __construct()

    protected $path_to_uploade_function = 'uploade/multi_uploade'; // path to function. you should change the path .("uploade" in this path is a CLASS' NAME)
    private $files = array();
    protected $default_css_path = 'assets/css';
    protected $default_javascript_path = 'assets/js';
    protected $path_to_dirrectory = 'assets/uploads/files/';
    // table description
    protected $file_table = 'files';
    protected $category_id_field = 'gallery_id';
    protected $file_name_field = 'file_name';
    protected $primary_key = 'file_id';

    function gallery()
        $crud = new grocery_CRUD();
        $crud->add_fields(array('title', 'photo'));
        $crud->callback_add_field('photo', array($this, 'add_upload_fied'));
        $crud->callback_edit_field('photo', array($this, 'edit_upload_fied'));
        $crud->callback_before_insert(array($this, '_set_files'));
        $crud->callback_after_insert(array($this, '_save_files_into_db'));
        $crud->callback_before_update(array($this, '_set_files'));
        $crud->callback_after_update(array($this, '_save_files_into_db'));
        // if you have no any upload fields on the page you should to set list of the JS files

        $output = $crud->render();

    function _set_js($crud)
        $crud->set_css('assets/grocery_crud/css/ui/simple/' . grocery_CRUD::JQUERY_UI_CSS);
        $crud->set_js('assets/grocery_crud/js/' . grocery_CRUD::JQUERY);
        $crud->set_js('assets/grocery_crud/js/jquery_plugins/ui/' . grocery_CRUD::JQUERY_UI_JS);

    function add_upload_fied()
        $html = '
<span class="fileinput-button qq-upload-button" id="upload-button-svc">
<span>Upload a file</span>
<input type="file" name="multi_aploade" id="multi_aploade_field" >
</span> <span class="qq-upload-spinner" id="ajax-loader-file" style="display:none;"></span>
<span id="progress-multiple" style="display:none;"></span>
<select name="files[]" multiple="multiple" size="8" class="multiselect" id="file_multiple_select" style="display:none;">
<div id="file_list_svc" style="margin-top: 40px;">
        return $html;

    function edit_upload_fied($value, $primary_key)
        $files = $this->db->get_where($this->file_table, array($this->category_id_field => $primary_key))->result_array();
        $html = '
<span class="fileinput-button qq-upload-button" id="upload-button-svc">
<span>Upload a file</span>
<input type="file" name="multi_aploade" id="multi_aploade_field" >
</span> <span class="qq-upload-spinner" id="ajax-loader-file" style="display:none;"></span>
<span id="progress-multiple" style="display:none;"></span>

        $html.= '<select name="files[]" multiple="multiple" size="8" class="multiselect" id="file_multiple_select" style="display:none;">';
        if (!empty($files))
            foreach ($files as $items)
                $html.="<option value=" . $items['file_name'] . " selected='selected'>" . $items['file_name'] . "</option>";
        $html.='<div id="file_list_svc" style="margin-top: 40px;">';
        if (!empty($files))
            foreach ($files as $items)
                if ($this->_is_image($items['file_name']) === true)
                    $html.= '<div id="' . $items['file_name'] . '">';
                    $html.= '<a href="' . base_url() . $this->path_to_dirrectory . $items['file_name'] . '" class="image-thumbnail" id="fancy_' . $items['file_name'] . '">';
                    $html.='<img src="' . base_url() . $this->path_to_dirrectory . $items['file_name'] . '" height="50"/>';
                    $html.='<a href="javascript:" onclick="delete_file_svc(this,'' . $items['file_name'] . '')" style="color:red;" >Delete</a>';
                    $html.='<div id="' . $items['file_name'] . '" >
                          <span>' . $items['file_name'] . '</span> 
                          <a href="javascript:" onclick="delete_file_svc(this,'' . $items['file_name'] . '')" style="color:red;" >Delete</a>
        return $html;

    function _is_image($name)
        return ((substr($name, -4) == '.jpg')
                || (substr($name, -4) == '.png')
                || (substr($name, -5) == '.jpeg')
                || (substr($name, -4) == '.gif' )
                || (substr($name, -5) == '.tiff')) ? true : false;

    function JS()
        $js = "<script>
function delete_file_svc(link,filename)
$('#file_multiple_select option[value=\"'+filename+'\"]').remove();
    $.post('" . base_url() . $this->path_to_uploade_function . "/delete_file', 'file_name='+filename, function(json){
        if(json.succes == 'true')
            console.log('json data', json);
    }, 'json');   
$(document).ready(function() {
         url: '" . base_url() . $this->path_to_uploade_function . "/uploade',
         sequentialUploads: true,
         cache: false,
          autoUpload: true,
          dataType: 'json',
          acceptFileTypes: /(\.|\/)(" . $this->config->item('grocery_crud_file_upload_allow_file_types') . ")$/i,
          limitMultiFileUploads: 1,
          beforeSend: function()
          progress: function (e, data) {
        $('#progress-multiple').html(string_progress + parseInt(data.loaded / data.total * 100, 10) + '%');
          done: function (e, data)
           $('#file_multiple_select').append('<option value=\"'+data.result.file_name+'\" selected=\"selected\">'+data.result.file_name+'</select>');
           var is_image = (data.result.file_name.substr(-4) == '.jpg'  
                                        || data.result.file_name.substr(-4) == '.png' 
                                        || data.result.file_name.substr(-5) == '.jpeg' 
                                        || data.result.file_name.substr(-4) == '.gif' 
                                        || data.result.file_name.substr(-5) == '.tiff')
                                                ? true : false;
         var html;
         html='<div id=\"'+data.result.file_name+'\" ><a href=\"" . base_url() . $this->path_to_dirrectory . "'+data.result.file_name+'\" class=\"image-thumbnail\" id=\"fancy_'+data.result.file_name+'\">';
         html+='<img src=\"" . base_url() . $this->path_to_dirrectory . "'+data.result.file_name+'\" height=\"50\"/>';
         html+='</a><a href=\"javascript:\" onclick=\"delete_file_svc(this,''+data.result.file_name+'')\" style=\"color:red;\" >Delete</a><div>';
        'transitionIn'	:	'elastic',
        'transitionOut'	:	'elastic',
        'speedIn'		:	600, 
        'speedOut'		:	200, 
        'overlayShow'	:	true
          html = '<div id=\"'+data.result.file_name+'\" ><span>'+data.result.file_name+'</span> <a href=\"javascript:\" onclick=\"delete_file_svc(this,''+data.result.file_name+'')\" style=\"color:red;\" >Delete</a><div>';

        return $js;

    function multi_uploade($action = NULL)
        switch ($action)
            case 'uploade':

            case 'delete_file':




    function uploade_file()
        $json = NULL;
        $config['upload_path'] = $this->path_to_dirrectory;
        $config['allowed_types'] = $this->config->item('grocery_crud_file_upload_allow_file_types');
        $config['encrypt_name'] = TRUE;
        $config['remove_spaces'] = TRUE;
        $config['max_filename'] = 0;
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('multi_aploade'))
            $json['error'] = $this->upload->display_errors();
            $json['success'] = 'false';
            $uploade_data = $this->upload->data();
            $json['success'] = 'true';
            $json['file_name'] = $uploade_data['file_name'];
        echo json_encode($json);

    function _set_files($post_array)
        $this->files = $post_array['files'];
        return $post_array;

    function _save_files_into_db($post_array, $primary_key)
        $this->db->delete($this->file_table, array($this->category_id_field => $primary_key));
        $files = array();
        if (!empty($this->files))
            foreach ($this->files as $file)
                $files[] = array($this->category_id_field => $primary_key, 'file_name' => $file);
        if (!empty($files))
            $this->db->insert_batch($this->file_table, $files);
        return true;

    function delete_file($file_name = NULL)
        $file_name = $this->input->post('file_name') ? $this->input->post('file_name') : $file_name;
        $this->db->delete($this->file_table, array($this->file_name_field => $file_name));
        if (file_exists($this->path_to_dirrectory . $file_name))
            unlink($this->path_to_dirrectory . $file_name);
        $json = array('success' => true);
        echo json_encode($json);

    function _example_output($output = null)
        $this->load->view('example', $output);


and then you should change JS code,

1) open this: 


2) change a function called clearForm like i typed bellow

	function clearForm()
		$('#crudForm').find(':input').each(function() {
	        switch(this.type) {
	            case 'password':
	            case 'select-multiple':
	            case 'select-one':
	            case 'text':
	            case 'textarea':
	            case 'checkbox':
	            case 'radio':
	                this.checked = false;

		/* Clear upload inputs  */
		/* -------------------- */		
		$('.chosen-multiple-select, .chosen-select, .ajax-chosen-select').each(function(){

As you see, it's only a few string and this functionality will work pretty well  :D

P.S: I'm hungry and angry today

P.S.S: Sorry for my English. I have no time to learn it.

P.S.S.S: I do not sell any fridges

#12701 Grocery_Crud_MultiSearch library for Flexigrid

Posted Akshay Hegde on 29 June 2015 - 12:00 PM

Hi ! Guys


This is my second small library which extends existing grocery_crud library this made my work easy so I just wanted to share with you guys, so that you can also make use of it. If If anyone wants to improve you are most welcome.


Please use below link to use the same





Guys I have plan to work on cookies (for multisearch) after sometimes, as I am busy with some project, please let me know difficulties you experienced, if any  or any useful feedback / suggestion for further improvements




Thank you


Akshay Hegde

#11516 Dependent Drop Down With Multiselect

Posted larasmith on 31 August 2014 - 07:06 AM

Finally I get this to work! :)  I just hope someone find this solution also useful for them...  :lol:


1. Get dependent items using ajax/jquery:

    Create a CONTROLLER that creates/receives the needed output based on the selected value on the drop down. I placed it on the same file that contains the controller that generates my datagrid. The file name is: "ctrl_gcrud.php"

public function get_funct_by_prog($progID)
	$mysqli = new mysqli("localhost", "USERNAME", "PASSWORD ", "DBNAME");
	$result = $mysqli->query("SELECT * FROM tblfunction WHERE funct_prog_id ='".$progID."'");		

	while($row_funct = mysqli_fetch_array($result))
             echo "<option value='".$row_funct['funct_id']."'>".$row_funct['funct_Name']."</option>";

2. Create a callback inside the same controller: "ctrl_gcrud.php". This call back is responsible for the following:

    a. Delete all elements from the multi-select: $("#field-Functions").find("option").remove();

    b. Add new elements in the multi-select: $("#field-Functions").html($response.responseText);

    c. Refresh "choosen select" plugin: $("#field-Functions").trigger("liszt:updated"); and $(".remove-all").trigger("click");

   Here is the code for the working callback:

	function tos_CBae_selFunc()
		return '
			<script type="text/javascript">
					$("#field-tos_prog_id").change(function() {
						var progID = $("#field-tos_prog_id").val();  
							         "url" :  "http://localhost/OCGA/ctrl_gcrud/get_funct_by_prog/"+ progID,      
							         "cache" : true,
							         "beforeSend" : function (){
							              //Show a message
							         "complete" : function($response, $status){
							             if ($status != "error" && $status != "timeout") {
							         "error" : function ($responseObj){
							             alert("Something went wrong while processing your request.\n\nError => "
							                 + $responseObj.responseText);
			' ;				

3. This is the controller that generates my datagrid: Notice the lines of code that is used to make our callback work.And here is the successful desired output:

	public function tos()
 		/*Create ajax_grocery_CRUD instead of grocery_CRUD. This extends the functionality with the
 		 field_set_defaults keeping all functionality as well (I extended this to grocery_CRUD)*/
		$crud = new ajax_grocery_CRUD();
		// Set theme

		// Set table name
		// Set this name instead of 'Record' in prompt
		$crud->set_subject('Table of Specification');
		//* These displays custom name instead of field name in columns						
		$crud->display_as('tos_course_DescTitle_id','Descriptive Title');
		$crud->display_as('tos_course_RefNo_id','Reference No.');			
		$crud->display_as('tos_lo_name_id','Learning Objective');
		$crud->display_as('tos_qtype_id','Question Type');
		$crud->display_as('tos_coglvl_id','Cognitive Level');
		$crud->display_as('tos_diffindex_id','Difficulty Index');
		$crud->display_as('tos_PilotTest_id','Pilot Tested');		

                // Sets relation with dependent dropdown list (Program->Function)

   		// Sets function (this must be dependent on the program)
         	$crud->set_relation_n_n('Functions', 'tbltos_funct', 'tblfunction', 'tos_id', 'funct_id', "{funct_Name}", 'priority');

		// This is the set of code for using the callback -*begin ppp
		$f=array'secret','tos_id','tos_assmntype_id','tos_prog_id','Functions','tos_sem_id','tos_qtype_id','tos_remarks_id','tos_reviewed_id','tos_status_id','tos_published_id','tos_PilotTest_id','tos_qry','tos_ctr','tos_need'); $crud->add_fields($f); $crud->edit_fields($f); $crud->callback_add_field('secret',array($this,'tos_CBae_selFunc')); $crud->callback_edit_field('secret',array($this,'tos_CBae_selFunc')); // -*end        

		// Sets dropdown list (Semester)

		// Sets dropdown list (QType)

		// Sets dropdown list (Remarks)

		// Sets dropdown list (Status)

		// Sets dropdown list (Reviewed bool)

		// Sets dropdown list (Published bool) then turn it as default value as text

		// Sets dropdown list (PilotTest bool) then turn it as default value as text

		//Removes the print feature $crud->unset_print();

		//**** These displays the output in the page
		$output = $crud->render();



Special thanks to the hints provided by none other than the grocery CRUD Hero himself: Sir Victor... It took me almost a month to get it though... I just hope this helps someone too.... This method is also tested working in multiselect created by using this code:

   	$this->db->select('funct_id, funct_Name');
	$results = $this->db->get('tblfunction')->result();
	$funct_multiselect = array();
	foreach ($results as $result) {
    	$funct_multiselect[$result->funct_id] = $result->funct_Name;
	$crud->field_type('tos_qry', 'multiselect', $funct_multiselect); 

Here is what it looks like:



Happy GCng!  :D

#10302 Power GroceryCrud

Posted Amit Shah on 08 December 2013 - 07:08 AM

Hi fellow GC forum members,


I hereby will like to share my new GC library - updated with 14 new features / enhancements to make it a Power GroceryCrud. With great thanks to Web-Johny to allow me create my new library over his existing one, i hereby share my extended / powered up GC.


Please note, i have been a GC developer using flexigrid. So all the changes that go in ... are with flexigrid. Other themes, you wonderful people are free to drop in and come up with your part of contribution to fill up the gaps in other themes. 


I have just plucked out the bits and pieces i have been using across all my projects and clubbed into one power pack library. It is not been tested 100% with the new combinations.. but i doubt it should fail as i have tested 80% of it in my last project - all combined.


Do update me in case anything crashes / falls out here - i surely will patch it so everyone can take the advantage of the same.


Happy GCing :)