AssamGuy
AssamGuy

Reputation: 1593

Performing in array like operation in smarty templates

I am working on a e-ticket booking system. When the user clicks ticket status, it should show the booked as well as available seats, in checkbox. Now I can perform this operation very well in PHP using in_array() function, but I need to show this on a different place. How could I show them?

I have both booked seats array and total number of seats. In PHP I used the following code to display them ( AJAX ):

$cnt = count($booked_seats);
for($i = 1; $i<=$total_seats; $i++) {
  if($i%10 == 0) {
    echo '<br />';
  }
  if(in_array($i,$booked_seats)) {
    echo '<input type="checkbox" disabled="disabled" checked="checked" />'.$i;  
  } else {
    echo '<input type="checkbox" name = "book[]" value = "'.$i.'" />'.$i;
  }
}

Upvotes: 1

Views: 3166

Answers (2)

Emmanuel Okeke
Emmanuel Okeke

Reputation: 1482

In the case of smarty 3, my answer is very similar to @Quasdunk 's the only difference being in the syntax of the in_array method. it's of the form:

{if in_array($needle,$array_element)}.....{/if}

So you would assign your content as explained by him but the loop would also be differentyou would instead have the following:

    {foreach $total_seats as $seat}
     {if $seat@iteration%10==0}
       <br />
     {/if}
     {if in_array($seat_no,$booked_seats)}
       <input type="checkbox" disabled="disabled" checked="checked" />{$seat}
     {else}
       <input type="checkbox" value="{$seat}" />{$seat}
     {/if}
   {/foreach}

Upvotes: 0

Quasdunk
Quasdunk

Reputation: 15230

The syntax for in_array() in Smarty is this:

{if $needle|in_array:$haystack_array}

So your loop would look something like this:

//php:

$smarty->assign('total_seats',$total_seats);
$smarty->assign('booked_seats',$booked_seats);

//in the template:

{foreach from=$total_seats item=seat_no name=seat_no}
  {if $smarty.foreach.seat_no.iteration % 10 == 0} <br /> {/if} 
  {if $smarty.foreach.seat_no.iteration|in_array:$booked_seats}
    <input type="checkbox" disabled="disabled" checked="checked" /> {$smarty.foreach.seat_no.iteration}
  {else}
   <input type="checkbox" name = "book[]" value = "{$smarty.foreach.seat_no.iteration}" /> {$smarty.foreach.seat_no.iteration}
  {/if}
{/foreach}

It's untested, but you get the idea...

Upvotes: 2

Related Questions