Search code examples
phphtmlsmarty

PHP Foreach with Smarty


I'm trying to make a dropdown list to work in Smarty from PHP, the data of the dropdown is from mysql.

I achieved this: Image

But is not working as a dropdown, it displays all data in one section.

This is the code I used below.

PHP

<?php
foreach ($options as $multiplier) {
  $option = "<option ";

  if ($multiplier == $results['multiplier']) {
    $option .= "selected=selected ";
  }

  $option .= "value=" . $multiplier . ">" . unesc($multiplier) . "</option>";

  $multi['option'] = $option;
  $multiplier_option[] = $multi;
}
$smarty->assign('multiplier_option', $multiplier_option);
unset($multiplier_option);

And HTML.

<tr>
  <td align='left' class='header'>{$lang_multiplier}:</td>
  <td align='left' class='lista' colspan='2'><select name='multiplier'>{foreach item=multi from=$multiplier_option}{$multi.option}{/foreach}</select></td>
</tr>

I can't figure out how to do it properly.


Solution

  • Let Smarty do the work for you.

    The html_options function will build the markup for you, just pass in your multipliers array for the values and output, and set the selected multiplier.

    $smarty->assign('multipliers', $options);
    $smarty->assign('selectedMultiplier', $results['multiplier']);
    
    <tr>
        <td align='left' class='header'>{$lang_multiplier}:</td>
        <td align='left' class='lista' colspan='2'>
            {html_options name=multiplier values=$multipliers output=$multipliers selected=$selectedMultiplier}
        </td>
    </tr>