Amit's Garage

A garage where one can get tools to solve their problems

Take control of the Add / Edit page

November 20, 2017 by BlakDronzer

PROBLEM

There are times when the users want to have control in the add / edit form. For example, there is a need to autoupdate a few fields based on the value set by user on one field. Such a scenario is a custom requirement rather then generic requirement. Hence there is no provision for the same.

SOLUTION

There is a simple solution for the same. One need to control the same with custom javascript. Lets figure out the steps / process involved in the same.

  1. Create a new javascript file. The same shall consist of a function that will trigger a capture of on blur event / on change event (whatever is required .. suitable for the situation).
  2. The same then can have the relevant piece of code that will make the changes elsewhere.
  3. Remember 1 thing .. this is very important point, we will not be able to use $.ready, instead use the following
    window.onload = function(){
        // Code. . .
    
    }
    
  4. The above is very important step and the simplest of reason for the same is, while this file gets loaded, the script yet is not loaded. The thing you need to do is tell crud to load this custom script. The same can be done using $crud->set_js() function.

The above is the mechanism you can attain control over add / edit / listing, anywhere as required.

A more prominent requirement / criteria that one may encounter like the query / requirement shared by the user in following link: https://www.grocerycrud.com/forums/topic/4106-showhide-field-from-dropdown/

Here the user wants to take control of the field to be shown / hidden when a value from dropdown is changed. For such scenario, as explained above, we need to hook an event in javascript to the dropdown. On change of the value in dropdown – we take a decision to either hide a field or show a field.

Every field in the GC add / edit form is encompassed in a div. Each such div is having a class attached which consist of <fieldname>_form_group. Using this, we can take control of the field container and show / hide – as required.

Happy GCing 🙂

 

 

Ambigious Field error when using relation

November 14, 2017 by BlakDronzer

Well,

PROBLEM
The base library of Grocerycrud still do have this issue of having ambigious field error. Why this occurs?  .. when we do a set relation and in the list, we try to run a search query, if it have overlapping / common field name in both the tables, then there are good chances of it having trouble of ambigous field issue as when the query is built upon, it is built using just the field name and not <table>.<field>name.

SOLUTION
Well – there is simple patch that once gone – the issue gets resolved.
Find the following function:


protected function set_ajax_list_queries($state_info = null)
{
....

In there, at the end of the function, replace the following (commented below) statement


//$this->or_like($column->field_name, $search_text);
$this->or_like($this->basic_db_table . "." . $column->field_name, $search_text);

Thats patch No.1.

Now, towards patch No. 2. Find the following function


protected function _get_field_names_to_search(array $relation_values)
{
....

In that, we need to add a patch the following line of code,


foreach($temp1 as $field)
	list($field_names_array[]) = explode('}',$field);

Now the additional patch


for($i=0; $i < count($field_names_array); $i++) { 
	$field_names_array[$i] = $this->_unique_join_name($relation_values[0]).'.'. $field_names_array[$i];

Thats it. That dose the trick of making a failsafe system and allowing you to have error free query even with common field in 2 tables in relation.

How to show all the records together

November 13, 2017 by BlakDronzer

Well, there are times – i actually want to have a feature to show all the records together rather having pagination. Now there is a little trick to the same – you don’t need to break your code to achieve the same.

There is a small trick to the same. The code – what it dose – is checks for some value in config. There are 2 config files to look in for – 1 is the config file found in application/config folder. Other config file is found in the themes – folder. What we need to look in is the

The default value set in there is –

$config['crud_paging'] = true;

. That – if you set it to false – you will have pagination but you still have all the records shown up together.

Now, but then there is a catch to the same … If we make the change this way – then the listing of all the records is applied across all the functions. If you want to limit the same, then there is a small trick to it without altering the code. ie. make a copy of the theme you wish to work with, rename the folder to some sensible name – limitlessflexigrid. Instead of using flexigrid, set the theme to limitlessflexigrid where ever you want to show all the records together. In this – set the flag value in the config file to be false. Thats it, there you will now have option to see all the records irrespective of the function and also control it where you want to.

Default values for Add Form

November 13, 2017 by BlakDronzer

SCENARIO

Grocerycrud by default dose not provide a solution for adding default values that can be utilized at the time of add form. But there are many a times a developer likes to have a default value set to the form.

SOLUTION

To achieve the same, one needs to either alter the base library to add the function or create one’s own extension. We at this solution will work on altering the base library to provide the same solution.

Open the GroceryCrud library file, find the following in the code ..

protected $callback_after_upload = null;

……there below the codes — add the following

protected $field_default_values = array();

Then u can find in for the following function ..

public function display_as($field_name,$display_as= null)

just before that or after – wherever you feel comfirtable, add the following


/**
*
* Function allows the user to set a default value to the the field set
* @param string $field
* @param string $value
*/
public function field_set_defaults($field,$value){
	$this->field_default_values[$field]=$value;
}

There you are now set to go with adding the mask to the fields you want.

Now post this…
Find the following….

protected function showAddForm()

……in here – add the following line


$data->field_values = $this->get_add_values(null);
$data->input_fields  = $this->get_add_input_fields($data->field_values);

Now you need to replace the existing get_add_input_fields function with the code below.


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

		$field_value = !empty($field_values) &amp;&amp; isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : null;

		if(!isset($this->callback_add_field[$field->field_name]))
		{
			$field_input = $this->get_field_input($field_info, $field_value);
		}
		else
		{
			$field_input = $field_info;
			$field_input->input = call_user_func($this->callback_add_field[$field->field_name], $field_value, null, $field_info);
			//make our little change
			//allow default field rendering behaviour if user returns false
			//in the callback
			if ($field_input->input === False) {
				$field_input = $this->get_field_input($field_info, $field_value);
			}
		}

		switch ($field_info->crud_type) {
			case 'invisible':
				unset($this->add_fields[$field_num]);
				unset($fields[$field_num]);
				continue;
				break;
		case 'hidden':
				$this->add_hidden_fields[] = $field_input;
				unset($this->add_fields[$field_num]);
				unset($fields[$field_num]);
				continue;
				break;
		}

		$input_fields[$field->field_name] = $field_input;
	}

	return $input_fields;
}

Now, how do we use it? Simple..


$crud->field_set_defaults('favorite_forum', &quot;GroceryCrud&quot;);

Happy GCing:)

JQuery Masking

November 13, 2017 by BlakDronzer

SCENARIO

Grocerycrud provides excellent solution for building backends. In the backend, to have prominent, efficient functionality one of the requirement is to have masking on the fields. Example – a zipcode / telephone no, etc. By default the functionality ain’t provided with Grocerycrud library.

SOLUTION

To achieve the same, one needs to either alter the base library to add the function or create one’s own extension. We at this solution will work on altering the base library to provide the same solution. To reach to the desired solution, we are going to use the masked library found at the following url

Open the GroceryCrud library file, find the following in the code ..

protected $callback_after_upload = null;

……there below the codes — add the following

protected $field_mask = null;

Then u can find in for the following function ..

public function display_as($field_name,$display_as= null)

just before that or after – wherever you feel comfirtable, add the following


/**
*
* Sets mask to the given field
* @param string $field
* @param string $mask
*/
public function mask_field($field , $mask)
{
$this->field_mask[$field] = $mask;
return $this;
}

There you are now set to go with adding the mask to the fields you want.

Now post this…
Find the following….

protected function showAddForm()

……in here – add the following line

$data->masks            = $this->field_mask;

Do the same for showEditForm

Now our work in the Grocerycrud library is done. Now we need to alter the Add / Edit templates of the theme. Open them and add the masked input library.
(i had downloaded and set it in my local so i can refer it directly using the code below. You can place it at the desired location of yours and point it in your template).
Add the entry to the page (you can add the same in the area where the scripts are mentioned / referred to)

$this->set_js($this->default_theme_path.'/flexigrid/js/jquery.maskedinput.js');

Now in the end, there is a script section. Will like you to alter and replace the same.

This script will set the masks to all the fields that are set by the user. The changes mentioned above are the same for add.php / edit.php

Now, how do we use it? Simple..


$crud->mask_field('phone', &quot;(999) 999-9999? x99999&quot;);

 

 

Conditional Multiselect

November 13, 2017 by BlakDronzer

SCENARIO
There are times when there is a need to have the multiselect data updated / refreshed based on the selection of some other fields. This link provides a classic example / requirement.

SOLUTION
Lets take the similar example to reach to the solution. What is needed is to update the list of all the actors based on the selection of the module. Following is a pattern that can be used to achieve the same.

  1. Create a JS file which will have a code to hook to the module_id (on change). What the code will do is – it will hit an ajax call on the backend – passing up the module_id selected by the user. In return it gets a json data that have all the actors in list that are not related to module_id selected.
  2. Now before you update the list of the mutiselect, what you can do is grab all the values of the options that the user had already selected. You can achieve the same by following piece of code.
    
    	var items[];
    	$('#field-actors option:selected').each(function(){
    		items.push($(this.val());
    	});
    	
  3. Now once you have grabbed the selected elements, empty up the field-actors. Now add up the newer elements to field-actors using jquery.
    
    	$("#field-actors").append("<option value='2999'>Amit Shah</option>");  ////this can be used to add the actors
    	.............................
    	$("#field-actors").append("<option value='1999' selected='selected'>AAAAAAA</option>");    /////This way u can set it to have it selected
    	

    The above is  just a sample as how u can add the same. For each element that you plan to add – if you found the same as it been selected by the user earlier, you can set it to be selected. Else you can have it set as regular option as shared above.

  4. Now what we have achieved is a refreshed / updated list of actors that dose not belong to module_id selected. Now simply update the options, refresh. The same can be achieved by the following piece of code.
    
    	$("#field-actors").multiselect('destroy');
    	$("#field-actors").multiselect();
    	

There, its all the piece of logic you can use to achieve a similar solution for your issues / requirements.

Happy GCing 🙂

Enhance Read / View

November 13, 2017 by BlakDronzer

SCENARIO

The library have a basic version of values being rendered during the time of read. Like for a boolean / tinyint – the value displayed is 1 / 0 .. rather it should be true or false.

SOLUTION

Here’s a solution to enhance the same.


/******Replace / Update the below function in the library******/
protected function get_read_input_fields($field_values = null)
{
	$read_fields = $this->get_read_fields();

	$this->field_types = null;
	$this->required_fields = null;

	$read_inputs = array();
	foreach ($read_fields as $field) {
		if (!empty($this->change_field_type)
			&& isset($this->change_field_type[$field->field_name])
			&& $this->change_field_type[$field->field_name]->type == 'hidden') {
			continue;
		}
		$this->field_type($field->field_name, 'readonly');
	}

	$fields = $this->get_read_fields();
	$types     = $this->get_field_types();

	$input_fields = array();

	foreach($fields as $field_num => $field)
	{
		$field_info = $types[$field->field_name];

		if(isset($field_info->db_type) && ($field_info->db_type == 'tinyint' || ($field_info->db_type == 'int' && $field_info->db_max_length == 1))) {
			$field_value = $this->get_true_false_readonly_input($field_info, $field_values->{$field->field_name});
		} else {
			$field_value = !empty($field_values) && isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : null;
		}
		if(!isset($this->callback_read_field[$field->field_name]))
		{
			$field_input = $this->get_field_input($field_info, $field_value);
		}
		else
		{
			$primary_key = $this->getStateInfo()->primary_key;
			$field_input = $field_info;
			$field_input->input = call_user_func($this->callback_read_field[$field->field_name], $field_value, $primary_key, $field_info, $field_values);
		}

		switch ($field_info->crud_type) {
			case 'invisible':
				unset($this->read_fields[$field_num]);
				unset($fields[$field_num]);
				continue;
				break;
			case 'hidden':
				$this->read_hidden_fields[] = $field_input;
				unset($this->read_fields[$field_num]);
				unset($fields[$field_num]);
				continue;
				break;
		}

		$input_fields[$field->field_name] = $field_input;
	}

	return $input_fields;
}

/***** Add the new functions to the library****/
protected function get_true_false_readonly_input($field_info,$value)
{
	$value_is_null = empty($value) && $value !== '0' && $value !== 0 ? true : false;
	$true_string = is_array($field_info->extras) && array_key_exists(1,$field_info->extras) ? $field_info->extras[1] : $this->default_true_false_text[1];
	$false_string =  is_array($field_info->extras) && array_key_exists(0,$field_info->extras) ? $field_info->extras[0] : $this->default_true_false_text[0];

	return $value === '1' || ($value_is_null && $field_info->default === '1') ? $true_string : $false_string;
}

protected function get_upload_file_readonly_input($field_info,$value)
{

	$this->load_js_fancybox();

	$this->set_js_config($this->default_javascript_path.'/jquery_plugins/config/jquery.fancybox.config.js');

	$unique = mt_rand();

	$uploader_display_none     = empty($value) ? " : "display:none;";
	$file_display_none      = empty($value) ?  "display:none;" : ";

	$is_image = !empty($value) &&
	( substr($value,-4) == '.jpg'
	|| substr($value,-4) == '.png'
	|| substr($value,-5) == '.jpeg'
	|| substr($value,-4) == '.gif'
	|| substr($value,-5) == '.tiff')
	? true : false;

	$image_class = $is_image ? 'image-thumbnail' : '';

	$file_url = base_url().$field_info->extras->upload_path.'/'.$value;

	$input = "
	<div id='success_$unique' class='upload-success-url' style='$file_display_none padding-top:7px;'>";
	$input .= "<a href='".$file_url."' id='file_$unique' class='open-file"; 
	//Code altered by Amit Shah - for the sake of using thumbnails 
	$_file_url = $field_info->extras->upload_path."/$value";
	//$input .= $is_image ? " $image_class'><img src='".$file_url."' height='50px'>" : "' target='_blank'>$value";
	$input .= $is_image ? " $image_class'>" . $this->img->rimg($_file_url, array('shortside'=>50, 'sharpen'=>true)) : "' target='_blank'>$value";
	//Code Alteration ends here
	$input .= "</a> ";
	$input .= "</div>
	<div style='clear:both'></div>

	";

	return $input;
}

The above code have helped me enhance the read view. This is the method one can use to enhance the same for further needs at ones end.

Copy New Row

November 13, 2017 by BlakDronzer

SCENARIO

There are times when a developer comes across a scenario / situation where he have a need to copy the existing content of a row in table to a new form. There might be just minor changes in the same. Rest all would be perfectly the same as it is for the previous row.

SOLUTION

To achieve the same, here is a set solution.

Find the following

class grocery_CRUD_States extends grocery_CRUD_Layout

……Then add the following row


const COPY_ROW = '20'; //This represent a new state that we need to handle in grocery crud

Find the following (just in that same class)


protected $states = array()

….Add the following


20 => 'copy'

Find the following function


public function getStateInfo() { ... }

…..Add the following case ..


case self::COPY_ROW: // copy
	if($first_parameter !== null)
	{
		$state_info = (object)array('primary_key' => $first_parameter);
	} else {
		throw new Exception('On the state &quot;copy&quot; the Primary key cannot be null', 6);
		die();
	}
	break;

///Here we need to have the primary key for us in order to copy the record

Now find the following


public function render() { .. }

…. Add the following piece of code in the same


case grocery_CRUD_States::COPY_ROW://copy
	if($this->unset_add)
	{
		throw new Exception('You don't have permissions for this operation', 14);
		die();
	}

	if($this->theme === null)
		$this->set_theme($this->default_theme);
	$this->setThemeBasics();

	$this->set_basic_Layout();
	//Set the default values
	$state_info = $this->getStateInfo();
	$this->copy_row($state_info);
	$this->showAddForm();
	break;

………..Just below the same function add the following


protected function copy_row($state_info) {
	$fields = $this->get_add_fields();
	$types     = $this->get_field_types();

	$field_values = $this->get_edit_values($state_info->primary_key);
	foreach($fields as $field)
	{
		$fieldName = $field->field_name;
		if(property_exists($field_values,$fieldName)) {
			if($types[$fieldName]->crud_type == 'upload_file') {
				//Make a copy of the same and then assign the new value to the same
				$oldFileName = $field_values->{$fieldName};
				$oldFileName = substr($oldFileName, 6);
				$newFileName = substr(uniqid(),-5).'-'. $oldFileName;
				$sourcePath = $types[$fieldName]->extras->upload_path . DIRECTORY_SEPARATOR . $field_values->{$fieldName};
				$newPath = $types[$fieldName]->extras->upload_path . DIRECTORY_SEPARATOR . $newFileName;
				if(is_file($sourcePath)) {
					copy($sourcePath, $newPath);
					$this->getModel()->set_add_value($field->field_name, $newFileName);
				}
			} else {
				$this->getModel()->set_add_value($field->field_name, $field_values->{$fieldName});
			}
		}
	}
}

Now find the following


protected function showAddForm() {..}

…. in here add the following


$data->field_values = $this->get_add_values(null);

…….Now find the following and comment the line

$data->input_fields     = $this->get_add_input_fields();

….instead — add the following


$data->input_fields  = $this->get_add_input_fields($data->field_values);

…..Now alter the following function .. just find and replace it with the one below


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];
		$field_value = !empty($field_values) &amp;&amp; isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : null;

		if(!isset($this->callback_add_field[$field->field_name]))
		{
			$field_input = $this->get_field_input($field_info, $field_value);
		} else {
			$field_input = $field_info;
			$field_input->input = call_user_func($this->callback_add_field[$field->field_name], $field_value, null, $field_info);
		}

		switch ($field_info->crud_type) {
			case 'invisible':
				unset($this->add_fields[$field_num]);
				unset($fields[$field_num]);
				continue;
				break;
			case 'hidden':
				$this->add_hidden_fields[] = $field_input;
				unset($this->add_fields[$field_num]);
				unset($fields[$field_num]);
				continue;
				break;
		}

		$input_fields[$field->field_name] = $field_input;
	}

	return $input_fields;
}

/*********************Noote 1 thing – u need to alter the grocery_crud_model and add following function there *******/


function set_add_value($field_name, $value) {
	$this->add_values[$field_name] = $value;
}
function get_add_values() {
	return (object) $this->add_values;
}

Please note: This piece of code is written a long time ago. In case there are any issues with the same, do let me know, will surely patch it with a fix.

Usually i would have had left solution without any explanations.. But i intend to go ahead and share my workaround on this scenario. GroceryCrud never was built up with a situation for copying a row. Sorry, don’t remember the name, but there was one contributor who came up with brilliant solution for setting default value for the add option. That is what clicked me to arrive to this solution.
Now What you mean by Copying the row – when needed – what we do is.. read the values from the previous row (the one to be copied) and set the values as default values to the new add form. That’s how this hack was built around.

GroceryCrud is designed to work around multiple functionalities from single controller’s method call (One may refer to the same as actions). This one is a well designed mini router defined around a controllers method. So what we do .. we add up our own route definition – const COPY …
Well, the actions (mentioned above) in GC are referred to as States. So we add our own state to the same.

Also add our piece of code where it retrieves the stateInfo.

Post setting up the StateInfo & State, we need to write our own handler for the state. The same is handled in the render method of the library. So we go and add our handler for the case (Copy) in the render method.

One of the functionality at the core what we have is – copy_row. There what we do is pull the value from the old record (the one to be copied from), and for each fields, set the relevant values to the new fields. Also takes care of the upload field. It don’t map the same value, but it rather copies file to new path and set the new file value to the same.

We additionally need to alter the GCModel file to set / get add field values.

One more thing before we show the add form..
We need to alter the input fields being generated to set the default values. That is where we alter it with get_add_input_fields.

Rest is all the game of updating the ShowAddForm where it makes the relevant calls to the required methods defined up earlier in the process.

And there you have your Copy Functionality baked and served.

Happy GCing 🙂

Add image uploader feature in Text Editor

November 13, 2017 by BlakDronzer

Scenario:
Grocerycrud have been majorly being used to build backend applications and therefore having a feature like uploading images from backend is very much a necessity if you want to use Grocerycrud as a tool for building your custom CMS (Content management system). But currently Grocerycrud dose not have in built support to do so.

Solution:
There are paid applications like CKFinder (which binds very well with CKEditor), but there is also an option which can be utilized for free. That is KCFinder (unfortunately the official site for the same is down but the link associated of sourceforge.net works fine.)

Now, in a brief – how to integrate the same with Grocerycrud.

  1. Download KCfinder
  2. Copy it to texteditor folder
  3. in kcfinder/conf/config.php enable config ‘disabled’ => false and set path to upload in ‘uploadURL’ => “your_folder”
  4. add some code in ckeditor config in assets/grocery_crud/js/jquery_plugin/config/jquery.ckeditor.config.js
     

$(function() {
        $('textarea.texteditor').ckeditor({
                language: 'en',
                extraPlugins : 'placeholder,youtube'
                toolbar: [
                ['Source','-','Save','NewPage','Preview','-','Templates'],
	  	['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
		['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
		['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
		'/',
		['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
		['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
		['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
		['Link','Unlink','Anchor','Youtube'],
		['Image','Flash','Table','HorizontalRule','Hhs','Smiley','SpecialChar','PageBreak'],
		'/',
		['Styles','Format','Font','FontSize'],
		['TextColor','BGColor'],
		['Maximize', 'ShowBlocks','-','About','CreatePlaceholder']

        ],
                //this code below for kcfinder           
                filebrowserBrowseUrl: '/assets/grocery_crud/texteditor/ckeditor/kcfinder/browse.php?opener=ckeditor&amp;amp;type=files',
                filebrowserImageBrowseUrl: '/assets/grocery_crud/texteditor/ckeditor/kcfinder/browse.php?opener=ckeditor&amp;amp;type=images',
                filebrowserFlashBrowseUrl: '/assets/grocery_crud/texteditor/ckeditor/kcfinder/browse.php?opener=ckeditor&amp;amp;type=flash',
                filebrowserUploadUrl: '/assets/grocery_crud/texteditor/ckeditor/kcfinder/upload.php?opener=ckeditor&amp;amp;type=files',
                filebrowserImageUploadUrl: '/assets/grocery_crud/texteditor/ckeditor/kcfinder/upload.php?opener=ckeditor&amp;amp;type=images',
                filebrowserFlashUploadUrl: '/assets/grocery_crud/texteditor/ckeditor/kcfinder/upload.php?opener=ckeditor&amp;amp;type=flash'



        });
        $('textarea.mini-texteditor').ckeditor({
                language: 'en',
                toolbar: 'Basic',
                width: 700
        });
        });

Add a new functionality to GroceryCrud base library

November 13, 2017 by BlakDronzer

SCENARIO
There are many a times requirements like the one mentioned here. As the scenario mentioned by here what user wants to achieve is a custom solution for the poject he is working on. As here, he wants to add 2 new buttons besides add. Similarly, there can be any such new functionalities that can be added to the core GC Library.

SOLUTION
(Here we will talk only about adding new buttons as expressed. The same can be replicated to add another functionalities. In near future, will share some of such functionalities that were added by me.)

One crude way is to alter the theme itself and add the buttons / functionality. It is a good practice if you wana replicate the same across all your site / application. Else, it is not. Other way around with the same pattern is, create a copy of the theme, rename it to something personal and use the same wherever the functionality is required.

Still, there is a simpler & better way around for the same.

(the following solution is to alter the base library to achieve the same solution. There is another mechanism too which i will like to share you in the next solution hence the base library remains intact and you can still achieve your own functionality with extended library version of yours.)

Open the GroceryCrud library file, find the following in the code ..


protected $callback_after_upload = null;

……there below the codes — add the following


protected $form_buttons = array();

……………….

Then u can find in for the following function ..


public function display_as($field_name, $display_as = null)

just before that or after – wherever you feel comfirtable, add the following


/**
*
* Allows user to add extra button to the add / edit form
* @param string $field
* @param string $mask
*/
public function form_buttons($button , $js_call,  $class=null)
{
$this->form_buttons[$button] = array('js_call'=>$js_call, 'class'=>$class);
return $this;
}

 

 

There you are now set to go with adding the buttons …
Mind it – here i am adding the button and it being handled by a js call – if u wish to – add it with a direct link / url .. etc. There is also a class that is used here for styling. Add your own styling with it. This is a functionality used by me .. but you surely can add it your way around. Add your required params ..etc

Now post this…

Find the following…..


protected function showList()

 

……in here – add the following line


$data->buttons = $this->form_buttons;

 

What we have accomplished is – we captured the users buttons ….whatever set by him…and now we going to use them in the list. Similarly – if you want the same to be added in the add / edit form – u can achieve it the same way without tempering the functional needs.

There is 1 last thing now required to accomplish is making alterations in the view template of GC
Find the suitable location where u need to add the following buttons – and just add the same


<?php
if(isset($buttons) && is_array($buttons) && count($buttons) > 0) {
$n=1;
foreach ($buttons as $formName => $frmConfig) {
if(array_key_exists('class', $frmConfig)) {
$class = $frmConfig['class'];
} else {
$class = 'btn btn-large';
}
?>
<div class='form-button-box'>
<input class='<?php echo $class?>' type='button' onclick='<?php echo 'javascript:' . $frmConfig['js_call'] . '()'?>'
value='<?php echo $formName; ?>' id='user-button_<?php echo $n?>' />
</div>
<?php }
} ?>

 

now, how to use the same?


$crud->form_buttons('Button Name', 'YourJSCall', 'SomeClass');

The class here can be left blank.
The JS functionality can be added to a custom js file which then can be added using


$cud->set_js('path/to/customJSFile');

Happy GCing 🙂

  • Search Knowledgebase