CodeIgniter repopulate form from both session data & form validation?

727 views Asked by At

I have a form with a couple search options, like a checkbox array and radio button. By using the form validation library I have the form repopulating after a submit, like so:

echo form_checkbox('check_track[]', '1', set_checkbox('check_track[]', '1', TRUE));
echo form_dropdown('select_year', $options, set_value('select_year', '2013'), $attribs);

I also save all the form options (by storing the post) into session userdata. Is it possible to repopulate all the fields from the session data if $_SERVER['REQUEST_METHOD'] !== 'POST' but keep repopulating based on form validation otherwise?

2

There are 2 answers

0
xref On BEST ANSWER

I ended up just faking that a POST had happened before the form validation stuff ran to get repopulation to work:

if(!isset($_POST['something']) && $this->session->userdata('something'))
{ 
        $_POST = $this->session->all_userdata(); 
}
$this->form_validation->set_rules('something', 'stuff', 'required');
.
.
.
0
yadutaf On

The easier would probably be to separate the form generation from the value generation. In the snippet you provide, the value is read directly from the submitted form.

I would advise you, in you controller or your model to generate a data structure, each field corresponding to one of the form field. For each, the value would either be the default, either the one stored in the session if it matches you condition ie: valid data and not after a POST if I understood you well.