Search code examples
phpsmartysmarty2

Assigning variable value in dropdown list in table


I have list of Materials as drop down in each row of table (100 rows). I want to selectively assign any row selected material.

For example, suppose $materialoptions is assigned an array (1=>'Material 1', 2=>'Material 2',3=>'Material 3'). This is list of dropdown in each row.

I want to assign in php say, In row 20, material selected is 'Material 2'.

Below is my implementation. Not able to assign properly. HTML/Smarty Code

<form name='materialsel' id='materialsel' method='POST' action=''>
<table>
{section name=counter start=1 loop=100 step=1}
  <tr>
    <td><SELECT name="materialid_{$smarty.section.counter.index}" id="materialid_{$smarty.section.counter.index}" onchange='return document.forms.materialsel.submit();'><option value='0'>Select Material</option>
 {html_options selected=$material_$smarty.section.counter.index options=$materialoptions}
   </SELECT>
      </td>
 </tr>
{/section}
 </table>
 </form>

PHP Code

$smarty->assign("materialoptions", array (1=>'Material 1', 2=>'Material 2',3=>'Material 3'));

//In row 20, material selected is 'Material 2'

$smarty->assign("material_20",2); //Not able to do this

Solution

  • You should change in your template file

    {html_options selected=$material_$smarty.section.counter.index options=$materialoptions}
    

    into

    {html_options selected=${"material_{$smarty.section.counter.index}"} options=$materialoptions}
    

    But in this case you should probably defined all material_1, material_2 and so on variables because you use them for option creation

    ** EDIT **

    You haven't mentioned that you need it in Smarty 2. Smarty 2 doesn't support variable variables so you should rethink of using other way to achieve this.

    In PHP instead of

    $smarty->assign("material_20",2);
    

    you should assign variables this way:

    $selections = array( '20' => 2);        
    $smarty->assign("selections", $selections);
    

    And in template file you should change

    {html_options selected=$material_$smarty.section.counter.index options=$materialoptions}
    

    into

    {html_options selected=$selections[$smarty.section.counter.index] options=$materialoptions}