How to re-populate check box in edit form using Co

2019-09-19 12:04发布

问题:

This question already has an answer here:

  • Re-populate checkbox if it fails in validation in an edit form in Codeigniter 5 answers

So far I know how to repopulate the form input and checkbox

It looks like that:

value="<?= set_value('rank') ?>" for input 

and

 <?= set_checkbox('is_default', '1'); ?> for checkbox

The problem is, how about in the edit form:

The input value is sofar ok:

value="<?= set_value('rank',$customer_group[0]['rank']); ?>"

but I can't repopulate the checkbox

<?php if ($customer_group[0]['is_default'] == "1") echo "checked"; set_checkbox('is_default', '1'); ?>

The checkbox will check even I have not check it in the edit => fail to validate in the form, thanks for helping

Update:

Is it correct if change to :

<?php
    if(isset($_POST['is_default']) || $customer_group[0]['is_default'] == "1"){
    echo "checked"; 
    }
    set_checkbox('is_default', '1'); 
 ?>

回答1:

A simple one just check for post data too if validation fails

<?php
    if(isset($_POST['is_default'])){
    echo "checked"; set_checkbox('is_default', '1');
    }elseif ($customer_group[0]['is_default'] == "1"){
    echo "checked"; set_checkbox('is_default', '1');
    }
 ?>

So if user checks checkbox and validation fails the form will have a checked check box as to save the choice made by user if there is no post data then it will be checked by database data that is in $customer_group