0

I have a form with validation. I want to keep the values of the form when the validation failed using set_value in the textboxes. These textboxes are using array for the name.

<input type="text" name="speed[]" value="<?php echo set_value('speed[]') ?>" />

I believe that this is exactly what is pointed out by the documentation here. But when the form submitted, I get "Array to string conversion" error. I wonder how to implement this properly.

1 Answer 1

0

You need to add an index between the square brackets in set_value.

Assuming you're using a loop to print the textboxes, you can do the following:

<?php for ($i = 0; $i < 10; $i++) : ?>
    <input type="text" name="speed[]" value="<?php echo set_value('speed['.$i.']') ?>" />
<?php endfor; ?>

And to validate/display errors for each field separately, set the validation rules in a loop:

for ($i = 0; $i < 10; $i++) {
    $this->form_validation->set_rules('speed['.$i.']', 'Speed', 'required');
}

Then you can use the index in form_error:

<?php for ($i = 0; $i < 10; $i++) : ?>
    <input type="text" name="speed[]" value="<?php echo set_value('speed['.$i.']') ?>" />
    <?php echo form_error('speed['.$i.']'); ?>
<?php endfor; ?>

Credits to this answer: https://stackoverflow.com/a/17802145/3960296

Sign up to request clarification or add additional context in comments.

1 Comment

Ah you're right! It works! Now I wonder how to populate the error message? I tried <?php echo form_error('speed['. $i .']') ?> but it was not showing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.