I have some some fields in a form that share the same name, they are automatically generated from a database table and I can't know how many would there be.
<div class="row w40 fl">
<label for="code" class="label">codice <span class="form-notice">*</span></label>
<input type="text" class="input" name="code" id="code" placeholder="Codice" value="<?= Input::post('code') ?>">
</div>
<div class="row w40 fr">
<label for="name" class="label">nome <span class="form-notice">*</span></label>
<input type="text" class="input" name="name" id="name" placeholder="Nome" value="<?= Input::post('name') ?>">
</div>
<?php foreach($categories as $cat): ?>
<div class="w20 fl">
<label for=""><?= ucwords($cat->name) ?></label>
<input type="checkbox" name="cat[]" value="<?= $cat->id ?>" <?= ($cat->id == Input::post('cat')) ? 'checked' : '' ?>>
</div>
<?php endforeach; ?>
The problem is that if a error occurs after the submit, all the checked inputs will be lost. If they would have different names there wouldn't be any problem, but they always different.
So after the submit, how can I remember the checked ones and check them ? Say the user check 5 of them, fills all the form inputs but leaves one blank. Obviously an error will pop out, but while all other inputs will have the data the user entered, the checkboxes won't, at least I don't know how to do it.
Note that Input::post('code') means (isset($_POST['code'])) ? $_POST['code'] : ''
Thank you, hope you can suggest me a solution.
Ok, so after more research here is the solution.
if ( isset($_POST['cat']) ) {
foreach ($_POST['cat'] as $cbCat) {
$selectedCat[$cbCat] = 'checked';
}
}
<?php foreach($categories as $cat): ?>
<div class="w20 fl">
<label for="cat-<?= $cat->id ?>"><?= ucwords($cat->name) ?></label>
<input type="checkbox" id="cat-<?= $cat->id ?>" name="cat[]" value="<?= $cat->id ?>" <?= (isset($selectedCat[$cat->id])) ? $selectedCat[$cat->id] : '' ?> >
</div>
<?php endforeach; ?>