Dacobah
Dacobah

Reputation: 789

On CodeIgniter, how to repopulate a form only with correct values?

Imagine a form like this:

<form action="test.php" method="post">
    <input type="text" name="firstname" value="<?=set_value('firstname')?>" />
    <input type="text" name="lastname" value="<?=set_value('lastname')?>" />
    <input type="text" name="email" value="<?=set_value('email')?>" />
    <input type="submit" name="submit_form" value="OK" />
</form>

If I submit an incorrect email, the CodeIgniter function will write "the field is not valid" and populate the invalid field with the wrong value.

I would like to keep the error message but not the wrong value (I prefer having an empty value). But I also want to keep the re-populating function for correct values.

Here is what I get:

http://nsa21.casimages.com/img/2011/12/29//111229060041170572.jpg

Here is what I want:

enter image description here

[EDIT] SOLUTION FOUND (thanks to Herr Kaleun and Matt Moore)

Example with the email field:

<input type="text" name="email" id="email" value="<?=!form_error('email')?set_value('email'):''?>" />

Upvotes: 3

Views: 4212

Answers (2)

Matt Moore
Matt Moore

Reputation: 581

The Form_error is set when a form value errors out based on the validation. Judging by your use of the set_value function I assume you're using the built in form validation. You can check to see if the message for that field is set if(form_error('fieldname') !=NULL) and set the value based on that.

You may have to setup error messages for each field, which you should be doing anyway. Here is the guide that covers it: http://codeigniter.com/user_guide/libraries/form_validation.html#repopulatingform

<form action="test.php" method="post"> 
    <input type="text" name="firstname" value="<?if(form_error('firstname') != NULL){echo set_value('firstname');}?>" /> 
    <input type="text" name="lastname" value="<?if(form_error('lastname') != NULL){ echo set_value('lastname');}?>" /> 
    <input type="text" name="email" value="<?if(form_error('email') !=NULL){ echo set_value('email');}?>" /> 
    <input type="submit" name="submit_form" value="OK" /> 
</form> 

*NOTE THIS CODE HAS NOT BEEN TESTED *

Upvotes: 1

Herr
Herr

Reputation: 2735

You can check the fields individually and have a logic like this.

If the error for a specific field is present, you can build a logic on top of that.

if ( form_error('email') != '' )
{
    $data['email_value'] = '';
}
else
{
    $data['email_value'] = set_value('email');
}

<form action="test.php" method="post">
    <input type="text" name="firstname" value="<?=set_value('firstname')?>" />
    <input type="text" name="lastname" value="<?=set_value('lastname')?>" />
    <input type="text" name="email" value="<?= $email_value; ?>" />
    <input type="submit" name="submit_form" value="OK" />
</form>

Upvotes: 2

Related Questions