⚠ In case you've missed it, we have migrated to our new website, with a brand new forum. For more details about the migration you can read our blog post for website migration. This is an archived forum. ⚠

  •     

profile picture

Asignar un valor por defecto a un campo / Add Field Default Value



John Faber Muñoz Paz

John Faber Muñoz Paz
  • profile picture
  • Member

Posted 20 October 2014 - 05:23 AM

Hola a todos!

Me gustaria saber si me podrian ayudar con un problemilla que tengo para asignar un valor por defecto a un campo en la base de datos, es algo muy sencillo:

Tengo una tabla TIDIOMA, la cual tiene algunos campos:

CREATE TABLE IF NOT EXISTS `tidioma` (
`ID` int(11) NOT NULL,
  `DESCRIPCION` varchar(45) NOT NULL,
  `ESTADO` varchar(45) NOT NULL DEFAULT '0',
  `FECHACREACION` datetime NOT NULL,
  `FECHAMODIF` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Mi problema es que al crear registros a traves del CRUD, no puedo asignarle un valor por defecto al campo `FECHACREACION`, ya intente de varias maneras:

  • Campo oculto ($this->crud->field_type('FECHACREACION', 'hidden', $value);)
  • con la función callback_add_field ($this->crud->callback_add_field('FECHACREACION',array($this,'_add_default_date_value'));)
public function _add_default_date_value(){
        $value = date("d/m/Y H:i:s");
        $return = '<input id="field-FECHACREACION" name="FECHACREACION" type="text" value="'.$value.'" maxlength="20" class="datepicker-input hasDatepicker" disabled="true">';
        return $return;
}

Y ninguna de estas me funcionó, lo único que quiero es asignarle la fecha del sistema a este campo, nada más. Les agradeceria mucho su ayuda :)

____________________________________________________________________________________________________________________

Hello everyone!
I wonder if I could help with a little problem that I have to assign a default value to a field in the database, it is very simple:
TIDIOMA have a table which has some fields:

CREATE TABLE IF NOT EXISTS `tidioma` (
`ID` int(11) NOT NULL,
  `DESCRIPCION` varchar(45) NOT NULL,
  `ESTADO` varchar(45) NOT NULL DEFAULT '0',
  `FECHACREACION` datetime NOT NULL,
  `FECHAMODIF` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

My problem is that when creating records through the crud, I can not assign a default value to the field `FECHACREACION`, and try in various ways:

  • hidden field ($this->crud->field_type('FECHACREACION', 'hidden', $value);)
  • function callback_add_field ($this->crud->callback_add_field('FECHACREACION',array($this,'_add_default_date_value'));)
public function _add_default_date_value(){
$value = date("d/m/Y H:i:s");
        $return = '<input id="field-FECHACREACION" name="FECHACREACION" type="text" value="'.$value.'" maxlength="20" class="datepicker-input hasDatepicker" disabled="true">';
        return $return;
}

And none of these worked for me, all I want is to assign the system date to this field, nothing more. We appreciate your help :)

 

 

 

 


Amit Shah

Amit Shah
  • profile picture
  • Member

Posted 21 October 2014 - 06:41 AM

Hi there,

 

Welcome to GC club

 

To achieve this simple functionality.. i will like you to add the following function calls to Grocery Crud library...

//Add the same under the following
class Grocery_CRUD extends grocery_CRUD_States {
..
..
         /* NEW */
	public function getModel() {
		if($this->basic_model === null)
	   		$this->set_default_Model();
	  	return $this->basic_model;
	}
	/* NEW */
	protected function get_add_values() {
		$values = $this->basic_model->get_add_values();
	  	return $values;
	}
.. ..
....
//Now under the showAddForm Function ... add the following code
    protected function showAddForm()
    { ..
      ..
      $data->field_values = $this->get_add_values(null);
      ....
      //Comment out the following line and add below the same
      //...$data->input_fields     = $this->get_add_input_fields();
      $data->input_fields  = $this->get_add_input_fields($data->field_values);     //or u can replace this with the line found above
      
      ///Now replace the following function with this new one
      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) && 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;
	}

This are so far the changes in the Grocery_CRUD.php library. Now add the following piece of code in the grocery_crud_model.php

/* NEW */
    function set_add_value($field_name, $value) {
      $this->add_values[$field_name] = $value;
    }

    /* NEW */
    function get_add_values() {
        return (object) $this->add_values;
    }

one last change.... now replace the add.php (view in the grocery_crud themes)  with the following

<?php

	$this->set_css($this->default_theme_path.'/flexigrid/css/flexigrid.css');
	$this->set_js_lib($this->default_theme_path.'/flexigrid/js/jquery.form.js');
	$this->set_js_config($this->default_theme_path.'/flexigrid/js/flexigrid-add.js');

	$this->set_js_lib($this->default_javascript_path.'/jquery_plugins/jquery.noty.js');
	$this->set_js_lib($this->default_javascript_path.'/jquery_plugins/config/jquery.noty.config.js');

?>
<div class="flexigrid crud-form" style='width: 100%;' data-unique-hash="<?php echo $unique_hash; ?>">
	<div class="mDiv">
		<div class="ftitle">
			<div class='ftitle-left'>
				<?php echo $this->l('form_add'); ?> <?php echo $subject?>
			</div>
			<div class='clear'></div>
		</div>
		<div title="<?php echo $this->l('minimize_maximize');?>" class="ptogtitle">
			<span></span>
		</div>
	</div>
<div id='main-table-box'>
	<?php echo form_open( $insert_url, 'class="form-horizontal form-bordered" method="post" id="crudForm" autocomplete="off" enctype="multipart/form-data"'); ?>
		<div class='form-div'>
			<?php
			$counter = 0;
				foreach($fields as $field)
				{
					$even_odd = $counter % 2 == 0 ? 'odd' : 'even';
					$counter++;
			?>
			<div class='form-field-box <?php echo $even_odd?>' id="<?php echo $field->field_name; ?>_field_box">
				<div class='form-display-as-box' id="<?php echo $field->field_name; ?>_display_as_box">
					<?php echo $input_fields[$field->field_name]->display_as; ?><?php echo ($input_fields[$field->field_name]->required)? "<span class='required'>*</span> " : ""; ?> :
				</div>
				<div class='form-input-box' id="<?php echo $field->field_name; ?>_input_box">
					<?php echo $input_fields[$field->field_name]->input?>
					<?php if(array_key_exists($field->field_name, $tips)) { ?>
					&nbsp;<span class="tips"><?php echo $tips[$field->field_name]?></span>
					<?php } ?>
				</div>
				<div class='clear'></div>
			</div>
			<?php }?>
			<!-- Start of hidden inputs -->
				<?php
					foreach($hidden_fields as $hidden_field){
						echo $hidden_field->input;
					}
				?>
			<!-- End of hidden inputs -->
			<?php if ($is_ajax) { ?><input type="hidden" name="is_ajax" value="true" /><?php }?>

			<div id='report-error' class='report-div error'></div>
			<div id='report-success' class='report-div success'></div>
		</div>
		<div class="form-actions" style="margin-left:20px; margin-top:-20px">
			<div class='form-button-box'>
				<input class='btn btn-primary btn-large' id="form-button-save" type='submit' value='<?php echo $this->l('form_save'); ?>'/>
			</div>
	<?php 	if(!$this->unset_back_to_list) { ?>
			<div class='form-button-box'>
				<input class='btn btn-darkblue btn-large' type='button' value='<?php echo $this->l('form_save_and_go_back'); ?>' id="save-and-go-back-button"/>
			</div>
			<div class='form-button-box'>
				<input class='btn btn-danger btn-large' type='button' value='<?php echo $this->l('form_cancel'); ?>' id="cancel-button" />
			</div>
	<?php 	}  ?>
			<div class='form-button-box'>
				<div class='small-loading' id='FormLoading'><?php echo $this->l('form_update_loading'); ?></div>
			</div>
			<div class='clear'></div>
		</div>
	<?php echo form_close(); ?>
</div>
</div>
<script>
	var validation_url = '<?php echo $validation_url?>';
	var list_url = '<?php echo $list_url?>';

	var message_alert_add_form = "<?php echo $this->l('alert_add_form')?>";
	var message_insert_error = "<?php echo $this->l('insert_error')?>";

</script>

I know this is the elongated version but this is what i use it and i get things all set - without issues

 

now to add / set default value to the add field just use it the following way

$crud->getModel()->set_add_value('max_concurrent', '5');

You might also find the same / other type of solutions on the forum - but hope this helps you achieve your solution.!!!

Happy GCing :)


John Faber Muñoz Paz

John Faber Muñoz Paz
  • profile picture
  • Member

Posted 27 October 2014 - 00:04 AM

Hi Amit,

I apologize for not giving an answer quickly, but I do not have my work per
Implement what you mentioned but I have a problem when trying to include a new language, errors are:

A PHP Error was encountered
Severity: Notice
Message: Undefined property: Idiomas::$add_values
Filename: core/Model.php
Line Number: 51
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: tips
Filename: views/add.php
Line Number: 39
A PHP Error was encountered
Severity: Warning
Message: array_key_exists() expects parameter 2 to be array, null given
Filename: views/add.php
Line Number: 39
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: tips
Filename: views/add.php
Line Number: 39
A PHP Error was encountered
Severity: Warning
Message: array_key_exists() expects parameter 2 to be array, null given
Filename: views/add.php
Line Number: 39

localhost_siget_idiomas_index_add.png

I was trying to validate that is what is wrong, but did not find the problem, I appreciate your coloboración advance :)


Amit Shah

Amit Shah
  • profile picture
  • Member

Posted 27 October 2014 - 08:34 AM

Sorry.. i missed on that tips part.. as my GC is all modified for my needs :(

 

for the issue to be resolved up - remove the code from line 30 to 41 .,. the following code

<?php if(array_key_exists($field->field_name, $tips)) { ?>
&nbsp;<span class="tips"><?php echo $tips[$field->field_name]?></span>
<?php } ?>

and add the following to the grocery_CRUD_Model class

protected $add_values = array();

this 2 changes should do the trick.