[eluser]iainco[/eluser]
Problem: Users select sports using HTML chechboxes and their selections are saved in a database. What is the best way of displaying checkboxes already selected for those which have been saved as selected?
Model
Code:
function fetchSports()
{
$sports = array();
$sport = $this->db->get('sport');
if($sport->num_rows() > 0)
{
$sports = $sport->result();
}
return $sports;
}
function fetchUserSports()
{
$count = 0;
$userSports = array();
$user_sport = $this->db->query('SELECT `sportID` FROM `user_sport` WHERE `userID` = ' . $this->db->escape($this->session->userdata('ID')));
foreach($user_sport->result() as $row)
{
$userSports[$count] = $row->sportID;
$count++;
}
return $userSports;
}
View
Code:
<? foreach($sports as $sport): ?>
<?=$sport->title?> <input type="checkbox" name="sports[]" value="<?=$sport->ID?>" <?=(in_array($sport->ID, $userSports)) ? 'CHECKED': '';?> /><br />
<? endforeach; ?>
Controller
Code:
function index()
{
$this->load->view('Profile_View', array('sports' => $this->Profile_Model->fetchSports(), 'userSports' => $this->Profile_Model->fetchUserSports()));
}
That's my first try, but it is terribly messy... I think my cold is preventing me from seeing a much more elegant solution!
*cries*