Repopulating the form fields using the Codeigniter form helper functions will not work when there is no validation associated to the form field. This post explains a solution that can be used to solve this issue.
The helper function set_value() is used for populating the values of the input boxes. The function rely on the CI form validation library for its purpose. The set_value() function looks for the value in the field object in the form validation library. But when there is no validation on a field the field object will not exists on the form validation class instance.
One simple way way to solve the issue is adding an empty validation to the field as given below.
$this->form_validation->set_rules("field_name","Field Name","");
The second way of solving the issue is by overwriting the set_value() helper function after extending the CI form helper. This can be done in below steps.
<?php
if ( ! defined('BASEPATH'))
exit('No direct script access allowed');
if ( ! function_exists('set_value'))
{
function set_value($field = '', $default = '')
{
$OBJ =&
_get_validation_object();
if ($OBJ === TRUE && isset($OBJ->_field_data[$field]))
{
return form_prep($OBJ->set_value($field, $default));
}
else
{
if ( ! isset($_POST[$field]))
{
return $default;
}
return form_prep($_POST[$field]);
}
}
}
/* End of file MY_form_helper.php */
/* Location: ./application/helpers/MY_form_helper.php */
The third way of solving the issue is by extending the CI form validation library. Please follow the below steps for extending the CI form validation library for solving the issue.
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
function set_value($field = '', $default = '') {
// no post?
if (count($_POST) == 0) {
return $default;
}
// no rules for this field?
if (!isset($this->_field_data[$field])) {
$this->set_rules($field, '', '');
// fieldname is an array
if ($this->_field_data[$field]['is_array']) {
$keys = $this->_field_data[$field]['keys'];
$value = $this->_traverse_array($_POST, $keys);
}
// fieldname is a key
else {
$value = isset($_POST[$field]) ? $_POST[$field] : FALSE;
}
// field was not in the post
if ($value === FALSE) {
return $default;
}
// add field value to postdata
else {
$this->_field_data[$field]['postdata'] = form_prep($value, $field);
}
}
return parent::set_value($field, $default);
}
}
Do you know that you can generate a complete PHP websites in minutes with PHP Website Generator?