Assign variable in smarty?
I have assigned two array to smarty : profiles
and selected_id
. profiles
array contains the array of all profiles and the selected_id
array c开发者_Go百科ontains ids of the profiles to be displayed .So I am displaying the all profiles like this :
<select id="countries" class="multiselect" multiple="multiple" name="profiles[]">
{foreach name = feach item = k from = $profiles}
<option value="{$k->bz_pro_id}">{$k->bz_pro_first_name} {$k->bz_pro_last_name}</option>
{/foreach}
</select>
Now I want to default select the ids that are already selected by admin . That means if I want to add selected = "selected"
in the option
of select
. For that I write :
{foreach name = feach item = k from = $profiles}
{foreach name = feach2 item = k2 from = $selected_id}
{if $k->bz_pro_id == $k2->bz_pro_id}
selected = "selected"
{/if}
{/foreach}
{/foreach}
So can I assign the select = "selected"
to a variable so that I can use it in the option
?
I have tested this, and it works. Assuming your arrays look something like this:
$profiles[] = array ( 'bz_pro_id' => '1', 'bz_pro_first_name' => 'test1', 'bz_pro_last_name' => 'test2');
$profiles[] = array ( 'bz_pro_id' => '2', 'bz_pro_first_name' => 'test3', 'bz_pro_last_name' => 'test4');
$selected_id = array('1');
The syntax you're using to access variables and array members isn't correct. This is the working solution:
<select id="countries" class="multiselect" multiple="multiple" name="profiles[]">
{foreach name=feach item=k from=$profiles}
<option value="{$k.bz_pro_id}"
{if in_array($k.bz_pro_id, $selected_id)}selected{/if}>
{$k.bz_pro_first_name} {$k.bz_pro_last_name}
</option>
{/foreach}
</select>
you can use following code.
<select id="countries" class="multiselect" multiple="multiple" name="profiles[]">
{foreach name = feach item = k from = $profiles}
<option value="{$k->bz_pro_id}" {if $k->bz_pro_id|in_array($selected_id)}selected = "selected"{/if} >{$k->bz_pro_first_name} {$k->bz_pro_last_name}</option>
{/foreach}
</select>
{assign var="name" value="Bob"}
Reference: http://www.smarty.net/docs/en/language.function.assign.tpl
精彩评论