andrew
andrew

Reputation: 5176

Smarty check selected checkboxes using array_search

I am trying to check checkboxes based on values in a smarty array.

In my php

$smarty->assign('locations_array',array(4,6,9,7));

I want to search through the array and if there is a match check the checkbox. Here is what I have tried in my template but I can't get it to work.I'm not sure how I can pass array_search the needle and haystack that it requires?

{foreach $locations as $x}
   {if $x.id == $x.id|@array_search:$locations_array}
   <label><input checked type="checkbox" name="locations[]" value="{$x.id}"/>{$x.title}</label>
   {else}
     <label><input type="checkbox" name="locations[]" value="{$x.id}" />{$x.title</label>
   {/if}
{/foreach}

Is this possible without creating a custom function?

Upvotes: 1

Views: 5336

Answers (3)

Chandresh M
Chandresh M

Reputation: 3828

i didnt works with array_search but i have some simply solution for your issue. you can check your checkbox value with the locations_array in the foreach loop.

 **$i = 0;**
        {foreach $locations as $x}
           **{if $x.id == $locations_array[$i]}**
           <label><input checked type="checkbox" name="locations[]" value="{$x.id}"/>{$x.title}</label>
           {else}
             <label><input type="checkbox" name="locations[]" value="{$x.id}" />{$x.title</label>
           {/if}
**$i++;**
        {/foreach}

Upvotes: 0

andrew
andrew

Reputation: 5176

For reference I think that this is the correct syntax when using array_search.

 {if $x.id|array_search:$locations_array}

where $x.id is the needle and $locations_array is the array haystack.
I decided to go for a different approach based on eknals feedback

Upvotes: 1

eykanal
eykanal

Reputation: 27047

Without actually answering your main question (I don't know whether you can pass two vars to the function from the template), this could all be avoided by making a new array instead of $locations in the php file. Just looking at your posted code, you would want each element to have three sub-elements: title, id, and checked. This way you can avoid having to compare across arrays in the template side, and you can also avoid having to write a custom function.

Upvotes: 1

Related Questions