michaelk46 wrote:I am trying to setup a page that uses a drop down menu to select which terms are used to search a database.
I also want to keep the same choice showing on the results page that was selected.
THis was suggested to me:
Code: Select all
public function formOptions($options, $value = NULL)
{
$html = NULL;
foreach($options as $key => $content)
{
if ($key == $value) $select = ' selected="selected"';
else $select = NULL;
$html .=
'<option value="' . htmlspecialchars($key) . '"' . $select .
'>' . htmlspecialchars($content) . '</option>' . "\n";
}
return $html;
}
and this is the template:
Code: Select all
<select name="unit_type_id">
<option value="0">Organization Type</option>
<?php echo $this->formOptions($this->unitTypePickList,$item->unitTypeId); ?>
</select>
I am on the verge of understanding it, but I can't quite grasp it.
Could one of y'all explain how this accomplishes that goal? Thanks in advance
This is why folks should document their code. Anyway, on to the explanation:
You make a call to the formOptions() method of whatever class (I'm assuming it's some controller), passing it 2 arguments: unitTypePickList, and unitTypeId - an array and an identifier, respectively.
The formOptions() method then creates an empty variable, $HTML, which will be used to store the rendered HTML. Duh. Then the method begins looping over the $options array (unitTypePickList) assigning the current index or the iteration to $key and the current index's value to $content. Within the foreach() loop, there is a conditional that checks whether $key == $value - this is where the 'selected' option element is decided; if a match is found, the $selected variable contains the HTML attribute 'selected="selected"'. Otherwise, it remains empty. Next, the HTML option element is constructed and concatenated onto the $HTML variable, including the $selected and $content variables in the output.
Once the loop is completed, the $HTML variable is returned to the caller (in this case, echo) and echo proceeds to output the data.
Simple.
Mark.