• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Set checkboxes from a join table

#1
[eluser]Andy UK[/eluser]
I'm a bit stuck with a checklist in the view... Here's the basic setup:

I have a Lifestyle Items table in my database... One row for each item. This is looped through to get a list of checkbox items in the view. All simple enough so far.

When checkboxes are selected and the property saved (we are dealing with lifestyle characteristics of a property), a join table is populated, with the property ID and the lifestyle ID. If three are checked, then we get three entries in the join table for example.

What I'm having trouble with is how to show the previous checked items in the view. I can get the items from the join table with a simple query based on the property ID, but not sure where to go from there.

Here is the view code

Code:
<ul>
   &lt;?php foreach($lifestyle_items as $item): ?&gt;
      <li>&lt;input id="lifestyle_&lt;?php echo $item-&gt;id ?&gt;" name="lifestyle_&lt;?php echo $item->id ?&gt;" type="checkbox" value="checked" /><label for="lifestyle_&lt;?php echo $item->id ?&gt;">&lt;?php echo $item->lifestyle_item ?&gt;</label></li>
   &lt;?php endforeach; ?&gt;
</ul>

#2
[eluser]JoostV[/eluser]
Say the result of your join is stored in array $selected_items. That array will then hold the selected item ids, right?

Code:
<ul>
   &lt;?php foreach($lifestyle_items as $item): ?&gt;
      <li>&lt;input id="lifestyle_&lt;?php echo $item-&gt;id ?&gt;" name="lifestyle_&lt;?php echo $item->id ?&gt;" type="checkbox"&lt;?php  !in_array($item->id, $selected_items) || print( checked="checked"'); ?&gt; /><label for="lifestyle_&lt;?php echo $item->id ?&gt;">&lt;?php echo $item->lifestyle_item ?&gt;</label></li>
   &lt;?php endforeach; ?&gt;
</ul> 

#3
[eluser]Andy UK[/eluser]
Thanks for the help! It was the in_array() function that sorted me out. I didn't know it existed until I saw it there!

#4
[eluser]JoostV[/eluser]
You're welcome Smile


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.