Home » Smarty

Creating selection list, using foreach and section loop in Smarty

16 July 2008 Share/Bookmark

In this article, I will be illustrating and explaining about foreach and section loop used in Smarty. I will be using these loops for creating a selection list.

We can create selection list from a custom Smarty function called ‘html_options’. html_options is a custom function that creates html option group with provided data. It takes care of which item(s) are selected by default as well. Required attributes are values and output, unless you use options instead.

<select name="user">
{html_options values=$id output=$names selected="4"}
</select>

Instead of html_options, we can also use loops to create the selection list. There are namely two loops in Smarty: 1) Section, and 2) Foreach

1) Template sections are used for looping over arrays of data. All tags must be paired with tags. Required parameters are name and loop. The name of the section can be anything you like, made up of letters, numbers and underscores. Sections can be nested, and the nested section names must be unique from each other. The loop variable (usually an array of values) determines the number of times the section will loop. sectionelse is executed when there are no values in the loop variable.

<select name="country">
{section name="getCountry" loop="$country"}
<option value="{$country[getCountry].country_id}" {if $country[getCountry].country_id eq '3'} selected {/if}>{$country[getCountry].country_name} </option>
{/section}
</select>

2) foreach loops are an alternative to section loops. foreach is used to loop over a single associative array. The syntax for foreach is much easier than section, but as a tradeoff it can only be used for a single array. foreach tags must be paired with /foreach tags. Required parameters are from and item. foreach loops can be nested, and the nested foreach names must be unique from each other. The from variable (usually an array of values) determines the number of times foreach will loop. foreachelse is executed when there are no values in the from variable.

<select name="country2">
{foreach item=country2 from=$country}
<option value="{$country2.country_id}" {if $country2.country_id eq '3'}selected{/if}> {$country2.country_name} </option>
{/foreach}
</select>

Download source code

Note: I have not included Smarty library files in this zip file. You can download the Smarty library files from http://smarty.php.net/download.php or directly from http://chapagain.googlecode.com/files/smarty.zip

Thank You.

From Mukesh Chapagain's Blog, post Creating selection list, using foreach and section loop in Smarty

email

php magento mukesh chapagain

Get New Post by Email
RSS Feed Subscribe RSS Feed
  • http://abhi-hiddentreasure.blogspot.com/ Abhi Khadka

    Looking great.. but some error in code.. please verify