4

When I try to populate a form field which is not required in form validation doesn't repopulate. Let's say I have a field but I don't want it to be required but I want it to be repopulated. How can I do it ? I think this is a bug for codeigniter.

SNaRe
  • 1,997
  • 6
  • 32
  • 68
  • What do you mean by repopulated? Do you mean you want to set the value of a field after a from is submitted but not valid? – Matthew Rapati Nov 18 '11 at 05:13
  • I want to repopulate a field which is not set as required in form validation rules. In form validation if you don't set a rule as required It doesn't populate it. – SNaRe Nov 18 '11 at 05:30
  • BTW; I think I solved the problem with a hack with helpers. But I'm really wondering a real solution. – SNaRe Nov 18 '11 at 05:43

3 Answers3

4

This piece of code solved my problem. But I have to use helpers for that. At least I have a solution.

function value_field($field, $default='') {
    return (isset($_POST[$field])) ? $_POST[$field] : $default;
} 
SNaRe
  • 1,997
  • 6
  • 32
  • 68
3

You have to set a validation rule on a field in order for it to repopulate on an invalid submission. Luckily, you can pass regular PHP functions, not just validation rules, to the set_rules() method so you could just set trim or something rather than required.

$this->form_validation->set_rules('your_field', 'Your Label', 'trim');

That will repopulate the field and not make it a required field.

Chris Schmitz
  • 8,097
  • 6
  • 31
  • 41
  • The problem is it only populates if I add 'required' to the rules. It doesn't populate if I write just trim|numeric etc. It wants required in that rule to populate. – SNaRe Nov 18 '11 at 06:11
  • Hmm... that shouldn't be the case. Does the form submission still fail if you remove the required rule? Also, are you extending the validation class and using any custom validation rules on the field(s)? – Chris Schmitz Nov 18 '11 at 14:20
  • I'm not extending it. But the next solution will be that I think. I will have to write my own. – SNaRe Nov 19 '11 at 08:33
  • Are you using `set_value()` to repopulate your form? If you could post your controller and view code that would help. – Chris Schmitz Nov 20 '11 at 22:43
1

Using the form helper's set_value() works even for non-required fields, I'm not sure where your problem lies...

echo form_input(array('name' => 'username', 'value' => set_value('username'));
Damien Pirsy
  • 25,319
  • 8
  • 70
  • 77