Hello
This is my second post, its about how to
fill DropDownList from Php using php with smarty template engine and jQuery
I am working on a project now I am using
php and smarty template engine, I need to fill drop down lists from php most of
you will tell me to use the classic way by printing the <select> tag with its option from php directly but as I said I am using smarty
template engine and I needed more efficient way so here was the solution for
doing that
At first I have created a function that
will take three parameters the name of dropdown list and the options array and a
flag
Function code
<?php
function FillDropDownList($name, $options, $selectOption = true)
{
global $Scripts;
if ($selectOption) {
$Scripts .= "\n$('select[name=$name]').append($(\"<option
/>\").val('-1').text('--Select--')); ";
}
foreach ($options as $var
=> $val) {
$Scripts .= "\n$('select[name=$name]').append($(\"<option
/>\").val('$val').text('$var')); ";
}
$Smarty->assign('Scripts',
$Scripts);
}
?>
Hint : I
am using jQuery Instead of regular JavaScript
As you can see
here I have generated a JavaScript code that will fill the drop down list with each
option in the array "options"
After generating
the code assign it to Scripts variable in smarty
And in my page I simply
add the following piece of code
<script type="text/javascript">
$(document).ready(function() {
{$Scripts}
});
</script>
Example of call
Php code:
$Options = array("First Option"=>"1", "Second
Option"=>"2", "Thired Option"=>"3");
FillDropDownList("dropdownlist", $Options, true);
$Smarty->display("template.tpl");
Template
<select name="dropdownlist"></select>
<script type="text/javascript">
$(document).ready(function() {
{$Scripts}
});
</script>
Example of
the output code
<select name="dropdownlist"></select>
<script type="text/javascript">
$(document).ready(function() {
$('select[name=dropdownlist]').append($("<option />").val('-1').text('--Select--'));
$('select[name=dropdownlist]').append($("<option />").val('1').text('First Option'));
$('select[name=dropdownlist]').append($("<option />").val('2').text('Second Option'));
$('select[name=dropdownlist]').append($("<option />").val('3').text('Thired Option'));
});
</script>
Example
of the UI output

