Minesh
Minesh

Reputation: 2302

Smarty template - trouble making checkbox values as selected for dynamic checkbox names

I have a several fields like for person's profile and for each field there are several options.

For e.g.

Age (10-15, 15-20, 20-25) 
Category (X, Y, Z)

and several other fields.

I have search page with all these fields along with their option values as check-boxes. So I am currently printing these values using below for-each loop

{foreach from=$field.options item=options}
<input name="{$field.field_search_name}[]" type="checkbox" value="{$options.url}" />
{$options.caption}
{/foreach}

Now issue is in making all the fields which are selected before submit, I need to show as selected from POST array.

I know that if we had static check-box name like "category[]" I could have done like below

{if in_array($options.url, $smarty.post.category)} checked {/if}

but in my case the check-box name is also dynamic and it is defined in smarty template only so I am not sure how to get work around for this. Something like below has to be worked on , please let me know if it is possible to do this in smarty.

{if in_array($options.url, $smarty.post.$field.field_search_name)} checked {/if}

Upvotes: 1

Views: 2915

Answers (1)

Danack
Danack

Reputation: 25711

If you want to have the check-boxes checked as per the POST fields set in the request you can access them through:

{if array_key_exists({$smarty.request, $field.field_search_name)}
    checked
{/if}

However that would depend on the input names being unique. If you're using field names with [] to make them be an array when the form is submitted, you should check on whether the value is in the array.

This requires a little hack to access the array:

{assign var=tempFieldName value=`$field.field_search_name`}

{if in_array({$smarty.request.$tempFieldName, $options.url)}
    checked
{/if}

To be honest though, I'd recommend generating a unique name for each input rather than putting several in the same name, and separating them using fieldName[] to push the values into the array anonymously. Doing that would reduce the issues you're seeing with not being able to access the POSTed variable directly.

Upvotes: 4

Related Questions