Welcome Guest, Not a member yet? Register   Sign In
Repopulating HTML select after failed form validation
#1

[eluser]richzilla[/eluser]
Hi all.

How would i got about repopulating an HTML select with the users input after failed validation. I can do it with normal text fields, just by using
Code:
<?php echo set_value('field'); ?>
however, i cant see anyway to do it with a dropdown.

Im using the CI form_dropdown function and ive got a default option (Please Select...), and a callback to ensure that users select something other than the default. However if a different field on the form fails validation, when the form is repopulated, the dropdown reverts to its default.

Any help would be appreciated.

Thanks
#2

[eluser]Flemming[/eluser]
Hi ricardino,

you should be able to do that with set_select();
#3

[eluser]richzilla[/eluser]
Thanks for the help.

Normally that would work, but my problem is that my dropdown is dynamically generated, so im never sure how many items will be in it. Is there anyway to integrate that with the form_dropdown method?
#4

[eluser]danmontgomery[/eluser]
The 3rd parameter of form_dropdown() is the selected value.

Code:
echo form_dropdown('fieldname', array( 1 => 'Value 1', 2 => 'Value 2'), 2);
#5

[eluser]frist44[/eluser]
I have a helper function that I don't have access to right now, but it takes a default value like the above. You could just send it to the post value as selected.

echo form_dropdown('fieldname', array( 1 => 'Value 1', 2 => 'Value 2'), $this->input->post('fieldname'));
#6

[eluser]bretticus[/eluser]
So I've been doing IT for about 2 months now (small company that just got smaller....hence my IT work.) I'll use that as my excuse for getting "CI-rusty." Anyways, I just got stumped up on this again. It took me some toil to remember that unless you declare a rule for each post field, when you have the validation object in play, set_value will look in the validation object for the postdata associated and find nada.

So here is how I handle this:

I set an empty rule with just the name of the post field like so:

Code:
$this->form_validation->set_rules('fieldname');

Now it works.

I wish CodeIgniter would reconsider this code decision.
#7

[eluser]taewoo[/eluser]
bretticus is correct
CI validation does this for you. Look at the user guide for CI validation library




Theme © iAndrew 2016 - Forum software by © MyBB