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   1561 downloads

__________________________________________

v 1.2.0 Attached File  gc_dependent_select.php   9.14K   4677 downloads
_______________________________________
v 1.1.1 Attached File  gc_dependent_select.php   6.64K   1025 downloads
_______________________________________
v 1.1.0 Attached File  gc_dependent_select.php   6.34K   956 downloads
The library v.1.1.0 has a bug!
http://www.grocerycr...t__20#entry4344
_______________________________________

How to use (v. 1.2.0.):
cc.jpg
c.jpg
 


$crud = new grocery_CRUD();
$crud->set_table('dd_goods');
$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');

$this->load->library('gc_dependent_select');
// 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;
$this->_example_output($output);

Note:

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:
schema.jpg


function test()
{
$crud = new grocery_CRUD();
$crud->set_table('zone_allocate_subzone');
$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');
$this->load->library('gc_dependent_select');

$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;

$this->_example_output($output);
}

---------------------------------------------------
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.




#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


#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,

 

so, PLEASE READ 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,

error_reporting(E_ALL);

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
<?php
class mymodel extends CI_Model  {
	
	function __construct()
	{
		parent::__construct();
		$this->load->database();
	}

        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);
	}


}

//controller.php
...
$this->load->model('mymodel');
$activities = $this->mymodel->get_activities_by_year("activities","2013");
foreach ($activities->result() as $row)
{
 $myarray[$row->id] .= $row->description;
}
$this->grocery_crud->field_type('interest_for','multiselect',$myarray);
...



#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() {
$(".various").fancybox();

//ADD IN A BUTTON TO ADD TO DROPDOWN
$('#countryID_input_box').append('<a href="<?=site_url()?>/examples/quick_add/" class="various fancybox.ajax">Add</a>');
});
</script>

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


function quick_add()
{
  //EDIT BELOW TO ADD YOU SELECT NAME VALUE
  $args = array(
'category_name' => 'select[name="countryID"]'
  );

  $javascript = '
  <script>
  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) {
//PREPEND DATA TO SELECT BOX
$(\''.$args['category_name'].'\').prepend(\'<option value="\'+data+\'">\'+category_text+\'</option>\');
//REBUILD SELECT BOX
$(\''.$args['category_name'].'\').trigger("liszt:updated");
//DISPLAY SUCCESS MESSAGE
$(\'#category_message\').html(\'Successfully inserted a new category\');
});
  }
  </script>
  ';

  $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>
  </div>
  ';

  echo $javascript.$html;
  exit;
}

function quick_add_save()
{
//POST ITEMS
$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);

//SAVE TO DATABASE
$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   3402 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)

 

<?php
$this->load->view('includes/header');
$this->load->view($content_view);
$this->load->view('includes/footer');

 

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...
    $data['content_view']='users/login';
    $this->load->view('template',$data);

  }

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)

 

<?php 
if(isset($css_files)){
      foreach($css_files as $style){
          echo '<link href="'.$style.'" rel="stylesheet"/>';
      }
}
if(isset($js_files)){
      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.
$data=array();
$data['variable1']='variable_value';
$data['variable2']=12;
$data['variable3']=array('subvariable1'=>'value1-1','subariable2'=>'value1-2');
//etc, then assign data to output.
$output->data=$data;
$this->load->view('template',$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.

 

Regards




#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   1205 downloads

Install:
1 - Please download Attached File  RTL.zip   10.64K   1205 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:
./application/

...

/modules/

/grocery_crud/

/config/

/controllers/

/libraries/

/models/

/views/

index.html

/welcome/

...


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:
$this->load->library('grocery_crud');

and add line#12:
$this->load->helper('url');
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 :)

 

Cheers

Johnny

 

 




#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




#887 Multiple search conditions on flexigrid

Posted Kenta Saito on 22 March 2012 - 01:04 PM

Version:
grocery_CRUD_v1.2.zip

To search with multiple conditions, I modified 3 files in grocery CRUD.

multiple.png

Form interface:
1. assets/grocery_crud/themes/flexigrid/views/list_template.php

Original:
<select name="search_field">
<input type="text" name="search_text">

Mine:
<select name="search_field[]">
<input type="text" name="search_text[]">
<select name="search_type[]"> (">=", "<"... etc. "" for 'like')
* repeat above as array.



Search engine:
2. application/libraries/grocery_crud.php

Oridinal:
$state_info->search

Mine:
$state_info->search[] (as array)


Other little things:
3. assets/grocery_crud/themes/flexigrid/js/flexigrid.js

To deal with Cookie made me confused. I turn it off this time.
Search clear button will clear all text.




Form interface:
1. assets/grocery_crud/themes/flexigrid/views/list_template.php
diff -ru --strip-trailing-cr CodeIgniter_2.1.0.orig/assets/grocery_crud/themes/flexigrid/views/list_template.php CodeIgniter_2.1.0/assets/grocery_crud/themes/flexigrid/views/list_template.php
--- CodeIgniter_2.1.0.orig/assets/grocery_crud/themes/flexigrid/views/list_template.php 2012-03-15 21:27:32.000000000 +0900
+++ CodeIgniter_2.1.0/assets/grocery_crud/themes/flexigrid/views/list_template.php 2012-03-21 14:45:12.000000000 +0900
@@ -52,13 +52,41 @@
  <form action='<?php echo $ajax_list_url?>' method='post' id='filtering_form' autocomplete = "off" >
  <div class="sDiv" id='quickSearchBox'>
   <div class="sDiv2">
-   <?php echo $this->l('list_search');?>: <input type="text" class="qsbsearch_fieldox" name="search_text" size="30" id='search_text'>
-   <select name="search_field" id="search_field">
+   <select name="search_field[]" id="search_field">
	 <option value=""><?php echo $this->l('list_search_all');?></option>
	 <?php foreach($columns as $column){?>
	 <option value="<?php echo $column->field_name?>"><?php echo $column->display_as?>&nbsp;&nbsp;</option>
	 <?php }?>
	</select>
+   <select name="search_type[]" id="search_type">
+	<option value="">like</option>
+	<option value="=">=</option>
+	<option value="&lt;&gt;">&lt;&gt;</option>
+	<option value="&lt;=">&lt;=</option>
+	<option value="&lt;">&lt;</option>
+	<option value="&gt;=">&gt;=</option>
+	<option value="&gt;">&gt;</option>
+	<option value="&lt;=&gt;">&lt;=&gt;</option>
+   </select>
+   <input type="text" class="qsbsearch_fieldox" name="search_text[]" size="30" id='search_text'>
+   <br />
+   <select name="search_field[]" id="search_field">
+	<option value=""><?php echo $this->l('list_search_all');?></option>
+	<?php foreach($columns as $column){?>
+	<option value="<?php echo $column->field_name?>"><?php echo $column->display_as?>&nbsp;&nbsp;</option>
+	<?php }?>
+   </select>
+   <select name="search_type[]" id="search_type">
+	<option value="">like</option>
+	<option value="=">=</option>
+	<option value="&lt;&gt;">&lt;&gt;</option>
+	<option value="&lt;=">&lt;=</option>
+	<option value="&lt;">&lt;</option>
+	<option value="&gt;=">&gt;=</option>
+	<option value="&gt;">&gt;</option>
+	<option value="&lt;=&gt;">&lt;=&gt;</option>
+   </select>
+   <input type="text" class="qsbsearch_fieldox" name="search_text[]" size="30" id='search_text'>
			 <input type="button" value="<?php echo $this->l('list_search');?>" id='crud_search'>
   </div>
		 <div class='search-div-clear-button'>


Search engine:
2. application/libraries/grocery_crud.php
diff -ru --strip-trailing-cr CodeIgniter_2.1.0.orig/application/libraries/grocery_crud.php CodeIgniter_2.1.0/application/libraries/grocery_crud.php
--- CodeIgniter_2.1.0.orig/application/libraries/grocery_crud.php 2012-03-15 21:27:32.000000000 +0900
+++ CodeIgniter_2.1.0/application/libraries/grocery_crud.php 2012-03-21 14:46:38.000000000 +0900
@@ -473,44 +473,88 @@
	 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 ($state_info->search as $search)
	{
-	if(isset($temp_relation[$state_info->search->field]))
+	$fields = array();
+	if ($search->type === '')
	 {
-	 if(is_array($temp_relation[$state_info->search->field]))
-	  foreach($temp_relation[$state_info->search->field] as $search_field)
-	   $this->or_like($search_field , $state_info->search->text);
+	 if($search->field != null)
+	 {
+	  if(isset($temp_relation[$search->field]))
+	  {
+	   if(is_array($temp_relation[$search->field]))
+	   {
+		foreach($temp_relation[$search->field] as $search_field)
+		 $fields[] = $search_field;
+	   }
+	   else
+		$fields[] = $temp_relation[$search->field];
+	  }
+	  else
+	  {
+	   $fields[] = $search->field;
+	  }
+	 }
+	 else
+	 {
+	  $columns = $this->get_columns();
+	
+	  #region temporary solution for the search with relation_n_n
+	  if(!empty($this->relation_n_n))
+	   foreach($columns as $num_row => $column)
+		if(isset($this->relation_n_n[$column->field_name]))
+		 unset($columns[$num_row]);
+	  #endregion
+	
+	  foreach($columns as $column)
+	   if(isset($temp_relation[$column->field_name]))
+		if(is_array($temp_relation[$column->field_name]))
+		 foreach($temp_relation[$column->field_name] as $search_field)
+		  $fields[] = $search_field;
+		else
+		 $fields[] = $temp_relation[$column->field_name];
+	   else
+		$fields[] = $column->field_name;
+	 }
+	 if (count($fields) == 1)
+	 {
+	  $this->like($fields[0], $search->text);
+	 }
	  else
-	  $this->like($temp_relation[$state_info->search->field] , $state_info->search->text);
+	 {
+	  $this->like('concat('.implode(', " ", ', $fields).')', $search->text);
+	 }
	 }
-	else
+	else
	 {
-	 $this->like($state_info->search->field , $state_info->search->text);
+	 if($search->field != null)
+	 {
+	  if(isset($temp_relation[$search->field]))
+	  {
+	   if(is_array($temp_relation[$search->field]))
+	   {
+		foreach($temp_relation[$search->field] as $search_field)
+		 $fields[] = $search_field;
+	   }
+	   else
+		$fields[] = $temp_relation[$search->field];
+	  }
+	  else
+	  {
+	   $fields[] = $search->field;
+	  }
+
+	  if (count($fields) == 1)
+	  {
+	   $this->where($fields[0].' '.$search->type, $search->text);
+	  }
+	  else
+	  {
+	   $this->where('concat('.implode(', " ", ', $fields).')'.' '.$search->type, $search->text);
+	  }
+	 }
	 }
	}
-   else
-   {
-	$columns = $this->get_columns();
-  
-	#region temporary solution for the search with relation_n_n
-	if(!empty($this->relation_n_n))
-	 foreach($columns as $num_row => $column)
-	  if(isset($this->relation_n_n[$column->field_name]))
-	   unset($columns[$num_row]);
-	#endregion
-  
-	$search_text = $state_info->search->text;
-  
-	foreach($columns as $column)
-	 if(isset($temp_relation[$column->field_name]))
-	  if(is_array($temp_relation[$column->field_name]))
-	   foreach($temp_relation[$column->field_name] as $search_field)
-		$this->or_like($search_field, $search_text);  
-	  else
-	   $this->or_like($temp_relation[$column->field_name], $search_text);	
-	 else
-	  $this->or_like($column->field_name, $search_text);
-   }
   }
  }

@@ -2309,19 +2353,25 @@
	 {
	  $state_info->order_by = $_POST['order_by'];
	 }
-	if(!empty($_POST['search_text']))
+	if (isset($_POST['search_text']))
	 {
-	 if(empty($_POST['search_field']))
+	 for ($i = 0; $i < count($_POST['search_text']); $i++)
	  {
+	  if(!empty($_POST['search_text'][$i]))
+	  {
+	   if(empty($_POST['search_field'][$i]))
+	   {
	  
-	  $search_text = strip_tags($_POST['search_field']);
+		$search_text = strip_tags($_POST['search_field'][$i]);
	  
-	  $state_info->search = (object)array( 'field' => null , 'text' => $_POST['search_text'] );
+		$state_info->search[] = (object)array( 'field' => null , 'text' => $_POST['search_text'][$i] , 'type' => $_POST['search_type'][$i] );
	  
-	 }
-	 else
-	 {
-	  $state_info->search = (object)array( 'field' => strip_tags($_POST['search_field']) , 'text' => $_POST['search_text'] );
+	   }
+	   else
+	   {
+		$state_info->search[] = (object)array( 'field' => strip_tags($_POST['search_field'][$i]) , 'text' => $_POST['search_text'][$i] , 'type' => $_POST['search_type'][$i] );
+	   }
+	  }
	  }
	 }
	break;


Other little things:
3. assets/grocery_crud/themes/flexigrid/js/flexigrid.js
diff -ru --strip-trailing-cr CodeIgniter_2.1.0.orig/assets/grocery_crud/themes/flexigrid/js/flexigrid.js CodeIgniter_2.1.0/assets/grocery_crud/themes/flexigrid/js/flexigrid.js
--- CodeIgniter_2.1.0.orig/assets/grocery_crud/themes/flexigrid/js/flexigrid.js 2012-03-15 21:27:32.000000000 +0900
+++ CodeIgniter_2.1.0/assets/grocery_crud/themes/flexigrid/js/flexigrid.js 2012-03-21 00:04:34.000000000 +0900
@@ -41,12 +41,12 @@
	 }
   });
  
-  createCookie('crud_page_'+unique_hash,crud_page,1);
-  createCookie('per_page_'+unique_hash,$('#per_page').val(),1);
-  createCookie('hidden_ordering_'+unique_hash,$('#hidden-ordering').val(),1);
-  createCookie('hidden_sorting_'+unique_hash,$('#hidden-sorting').val(),1);
-  createCookie('search_text_'+unique_hash,$('#search_text').val(),1);
-  createCookie('search_field_'+unique_hash,$('#search_field').val(),1);
+//  createCookie('crud_page_'+unique_hash,crud_page,1);
+//  createCookie('per_page_'+unique_hash,$('#per_page').val(),1);
+//  createCookie('hidden_ordering_'+unique_hash,$('#hidden-ordering').val(),1);
+//  createCookie('hidden_sorting_'+unique_hash,$('#hidden-sorting').val(),1);
+//  createCookie('search_text_'+unique_hash,$('#search_text').val(),1);
+//  createCookie('search_field_'+unique_hash,$('#search_field').val(),1);
  
   return false;
  });
@@ -58,7 +58,8 @@

  $('#search_clear').click(function(){
   $('#crud_page').val('1');
-  $('#search_text').val('');
+  $("[name='search_text[]']").val('');
+
   $('#filtering_form').trigger('submit');
  });



#5775 Login Screen

Posted davidoster on 15 February 2013 - 12:10 PM

If you use the ion_auth library it has a builtin table of user_groups.

There you create your groups.

Then you create on more table called group_priviledges.

group_priviledges table has id, group_id, description [even a url, or function name] as a list of all the available priviledges.

Then you assign your users to groups.

And you get (via your model) a true false value if the current operation(make an add/delete/update, redirect to x url, or call y function) is allowed for this user(group).

 

You make the system once and then you forget it for ever.

And you have a nice grocery crud interface to add/update all these data!




#4528 Error in Flexigrid search when using relations between 2 tables that contain...

Posted Eran on 30 November 2012 - 10:32 PM

Hi,
I recently moved from using datatables to using flexigrid. After a couple of days I noticed that when I try to use the search feature, the ajax call returns a "500 Internal Server" error.
I started playing with my code and I noticed that when I stop using "set_relation" the search was working again. So I started thinking that maybe the automatically generated SQL query is some how incorrect.
In order to get the actual query sent to the MySQL driver, I added a file_put_content directive at the end of the "_compile_select" function in codeigniter DB_active_rec.php.
The generated SQL query was indeed incorrect. The issue was that the relation is translated into a JOIN. If the joined tables contain fields with the same name, the search query will fail because they both contain the same field and therefor it's ambiguous. This would not happen if the field names would include a table name (e.g. table_name.field_name instead of just field_name).

To make this clearer I'll give you an example:
I have a table called t_deploy_groups. It's SQL schema and data:
--
-- Table structure for table `t_deploy_groups`
--
DROP TABLE IF EXISTS `t_deploy_groups`;
/*!40101 SET @saved_cs_client	 = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `t_deploy_groups` (
`dgID` int(11) NOT NULL AUTO_INCREMENT,
`userID` int(11) NOT NULL,
`dgName` varchar(256) NOT NULL,
`dgDescription` varchar(1000) NOT NULL,
`sameAsDG` int(11) DEFAULT NULL,
PRIMARY KEY (`dgID`)
) ENGINE=InnoDB AUTO_INCREMENT=1114 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `t_deploy_groups`
--
LOCK TABLES `t_deploy_groups` WRITE;
/*!40000 ALTER TABLE `t_deploy_groups` DISABLE KEYS */;
INSERT INTO `t_deploy_groups` VALUES (1,1,'Telus','Telus Labs',NULL),(3,1,'T-Mobile','T-Mobile POS',NULL),(67,1,'AT&T','AT&T POS',NULL),(300,1,'QA','Testing & QA',1),(1111,1,'Demo','Playground',NULL);
/*!40000 ALTER TABLE `t_deploy_groups` ENABLE KEYS */;
UNLOCK TABLES;

The sameAsDG field should contain an existing dgID. So when I display this table using grocery crud, I added a set relation on the sameAsDG that will show you the existing names of the existing deploy groups (in this example the relation is from the table onto itself).

My controller code is:
public function deploy_groups() {
$uid = $this->session->userdata('uid');
$crud = new grocery_CRUD();
$crud->set_table('t_deploy_groups')
->set_subject('Deploy Group')
->required_fields('userID', 'dgName', 'dgDescription')
->display_as('dgName', 'Deploy Group Name')
->display_as('dgDescription', 'Deploy Group Description')
->display_as('sameAsDG', 'Use Same Apps As')
->display_as('dgID', 'ID')
->columns('dgID', 'dgName', 'dgDescription', 'sameAsDG')
->fields('dgID', 'dgName', 'dgDescription', 'sameAsDG');
$crud->set_relation('sameAsDG', 't_deploy_groups', 'dgName', "t_deploy_groups.userID = $uid", 'dgName ASC')
->callback_insert(array($this->simon_model, 'deploy_group_insert_callback'))
->callback_after_delete(array($this->simon_model, 'deploy_group_after_delete_callback'))
->where("t_deploy_groups.userID = $uid");
$crud->unset_add()
->unset_edit()
->unset_delete()
->unset_print();
$output = $crud->render();
$output->active = 'deploy_groups';
$this->load->view('deploy_groups.php', $output);
}

In my application the table looks like this:
dg_table_screenshot.png

If you try to search for the word "POS" you would expect to see 2 rows (becuase they are the only ones that contain this word), but you will get all the rows because the ajax search call would fail.

The automatic SQL query used is:
SELECT *
FROM (`t_deploy_groups`)
LEFT JOIN `t_deploy_groups` as ja7d8fa27 ON `ja7d8fa27`.`dgID` = `t_deploy_groups`.`sameAsDG`
WHERE `t_deploy_groups`.`userID` = 1
AND `dgID` LIKE '%POS%'
OR `t_deploy_groups`.`dgName` LIKE '%POS%'
OR `dgDescription` LIKE '%POS%'
OR `ja7d8fa27`.`dgName` LIKE '%POS%'
HAVING `t_deploy_groups`.`userID` = 1

If you try to run this query directly through MySQL you will get: "Error Code: 1052. Column 'dgID' in where clause is ambiguous"

If the field names in the where section would include the table name (t_deploy_groups), this query would be correct.


In order to fix this issue I added the following function to the grocery_CRUD_Model class in the grocery_crud_model.php file:
/**
	 * We use this function to make sure that the format for each field is <table_name>.<field>
	 * @param string $field
	 * @return string
	 */
function long_field_name($field)
{
if ((!is_null($this->table_name)) && (trim($this->table_name) != '') && (strpos($field, '.') === false)) {
	 return "$this->table_name.$field";
} else {
	 return $field;
}
}

This code adds the table name to the field name if it doesn't already exists.

I added a call to this function in the following functions: like() and or_like() (both are in the grocery_crud_model.php file)
function like($field, $match = '', $side = 'both')
{
	 $this->db->like($this->long_field_name($field), $match, $side);
}

function or_like($field, $match = '', $side = 'both')
{
	 $this->db->or_like($this->long_field_name($field), $match, $side);
}

I also changed the _get_field_names_to_search() function from the grocery_crud.php file:
protected function _get_field_names_to_search(array $relation_values)
{
  if(!strstr($relation_values[2],'{'))
	  return $this->_unique_join_name($relation_values[0]).'.'.$relation_values[2];
  else
  {
   $relation_values[2] = ' '.$relation_values[2].' ';
   $temp1 = explode('{',$relation_values[2]);
   unset($temp1[0]);
  
   $field_names_array = array();
   foreach($temp1 as $field)
    list($field_names_array[]) = explode('}',$field);
  
   //New Code - this was added to make sure that relations using more than one field in the
   //$related_title_field paramter, will be using the unique table name infront of the field name 
   foreach ($field_names_array as $key => $field) {
	   $field_names_array[$key] = $this->_unique_join_name($relation_values[0]).'.'.$field;
   }
   return $field_names_array;
  }
}

The change is the additional foreach following the "New Code" comment. This was added to handle a situation where you have a complex $related_title_field (e.g. "{dgID} - {dgName}"). Without this addition these fields might not get the correct table name added to them (happens when your relation is between 2 different tables).  


This fixed the issue for me. And now the Flexigrid search is working in all my views.

You can probably work around this in several other ways (like using a view with unique field names), but this way works for me.
Hope this might help other people that are stuck on the same issue.

Johnny, what do you think about adding something like this to the code?


#3085 set_relation_n_n where clause

Posted goFrendiAsgard on 23 August 2012 - 05:11 AM

I've just add where clause to set_relation_n_n.
Here is the changes: https://github.com/s...d/pull/88/files

Here is the usage example:
$crud->set_relation_n_n('teachers',
				'sch_schoolyear_subject_teacher', 'sch_teacher',
				'schoolyear_subject_id', 'teacher_id',  'name',
						null, array('active'=>1));
Hope it will help someone :)


#2 Items added to the library: file validation , Create thumbnail for your image...

Posted Moslem Mansouri on 16 October 2011 - 05:13 PM

Hello to all my friends


I'll congratulate the opening of the forum
This useful little library in my upload and delete files, edit it
Items added to the library:
1 - file validation.
2 - Create thumbnail for your images.
3 - Add numbers to the last file in the file name to avoid interference

function upload_file find, and the following change:
protected function upload_file($state_info)
{
  if(isset($state_info->field_name) && isset($this->upload_fields[$state_info->field_name]))
  {
   $upload_info = $this->upload_fields[$state_info->field_name];
  
			// Set useful variables
   $upload_path = $this->upload_fields[$state_info->field_name]->upload_path . '/';
   $file_type = $this->upload_fields[$state_info->field_name]->file_type;
   $thumbnail = $this->upload_fields[$state_info->field_name]->thumbnail;
   $upload_file = explode('.', $state_info->file_name);
   $upload_file_ext = end($upload_file);
   $upload_file_name = substr($state_info->file_name, 0, ((strlen($upload_file_ext)+1)*-1));
   $upload_file_name_orig = $upload_file_name;
  
  
   if($file_type != NULL)
   {
	$file_type_array = explode('|',$file_type);
	if(!in_array($upload_file_ext,$file_type_array))
	{
	 //return FALSE;
	}
   }
   // Create upload path folder if it doesn't already exist
   if (!is_dir($upload_path)) {
	mkdir($upload_path);
   }
   $i = 1;
   while(file_exists($upload_path . $upload_file_name . '.' . $upload_file_ext)){
	// Our file exists. Rename.
	$upload_file_name = $upload_file_name_orig . '_' . $i;
	$state_info->file_name = $upload_file_name . '.' . $upload_file_ext;
	$i++;
   }
   $input = fopen("php://input", "r");
		 $temp = tmpfile();
		 $realSize = stream_copy_to_stream($input, $temp);
		 fclose($input);
		
		 $target = fopen("{$upload_info->upload_path}/{$state_info->file_name}", "w");
		 fseek($temp, 0, SEEK_SET);
		 stream_copy_to_stream($temp, $target);
		 fclose($target);
		
			if($thumbnail != NULL)
   {
	// Create Thumbnail folder if it doesn't already exist
	if (!is_dir($upload_path . "Thumbnail")) {
	 mkdir($upload_path . "Thumbnail");
	}
	// File Uploaded
	$thumbnail_array = explode('|',$thumbnail);
	$config = array (
	'source_image'  => $upload_path . $state_info->file_name,
	'new_image'   => $upload_path . "Thumbnail/" . $state_info->file_name,
	'maintain_ration' => FALSE,
	'width'	=> $thumbnail_array[0],
	'height'   => $thumbnail_array[1]
	);
	// Generate the Thumbnail If Is Image
	$ci = &get_instance();
	$ci->load->library('image_lib', $config);
	if ( ! $ci->image_lib->resize())
	{
	 //return FALSE;
	}
   }
		 return (object)array('file_name' => $state_info->file_name);
  }
  else
  {
   //return false;
  }
}

function delete_file find, and the following change:
protected function delete_file($state_info)
{
  if(isset($state_info->field_name) && isset($this->upload_fields[$state_info->field_name]))
  {
   $upload_info = $this->upload_fields[$state_info->field_name];
  
   if(file_exists("{$upload_info->upload_path}/{$state_info->file_name}"))
   {
	if( unlink("{$upload_info->upload_path}/{$state_info->file_name}") )
	{
	 $this->basic_model->db_file_delete($state_info->field_name, $state_info->file_name);
	 if(file_exists("{$upload_info->upload_path}/Thumbnail/{$state_info->file_name}"))
	 {
	  unlink("{$upload_info->upload_path}/Thumbnail/{$state_info->file_name}");
	 }
	 return true;
	}
	else
	{
	 return false;
	}
   }
   else
   {
	$this->basic_model->db_file_delete($state_info->field_name, $state_info->file_name);
	return true;
   }
  }
  else
  {
   return false;
  }
}

function set_field_upload find, and the following change:
/**
*
* Enter description here ...
* @param string $field_name
* @param string $upload_path
* @param array $File_type
*/
public function set_field_upload($field_name, $upload_path , $file_type = NULL , $thumbnail = NULL)
{
$upload_path = substr($upload_path,-1,1) == '/' ? substr($upload_path,0,-1) : $upload_path;
$this->upload_fields[$field_name] = (object)array( 'field_name' => $field_name , 'upload_path' => $upload_path , 'file_type' => $file_type , 'thumbnail' => $thumbnail);
}




Finished editing the library. Now consider the following example:
function news()
{
try{
$crud = new grocery_CRUD();
$crud->set_table('news');

//$crud->set_field_upload('Fild Name','Path Of Upload' [, 'File Type Validate , 'Thumbnail Width|Thumbnail Height']);

// Upload Without Validate And Thumbnail
$crud->set_field_upload('mp3','songs');

// Upload Without Thumbnail
$crud->set_field_upload('mp3','songs' , 'mp3');
$crud->set_field_upload('poster','images/songs' , 'jpg|jpeg|gif|png');

// Upload With Validate And Thumbnail
$crud->set_field_upload('picture','images/news' , 'jpg|jpeg|gif|png' , '25|25');
$output = $crud->render();
$this->_example_output($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}


Which is very useful for me
I hope you will also be useful for
...................................................................

M sorry for my poor English
---------------------------------------------------------------------------------------------------

Changes in the code:
I added a few lines of code
Some friends had a problem with the product thumbnail and thumbnail folders themselves did not know who should build the project.
I added the code to the destination folder and auto-thumbnailing not need to build it manually.

// Create upload path folder if it doesn't already exist
if (!is_dir($upload_path)){
mkdir($upload_path);
}
// Create Thumbnail folder if it doesn't already exist
if (!is_dir($upload_path . "Thumbnail")) {
mkdir($upload_path . "Thumbnail");
}

Admin please add this code in the next version of the library
Thanks Dear Admin


#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

 

https://github.com/A...rud_MultiSearch

 

 

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