1

I wrote a basic Smarty modifier that emulates JavaScript's push.

function smarty_modifier_push($array, $push){
    if(!isset($array)){
        $array = array($push);
    }elseif(is_array($array)){
        $array[] = $push;
    }
    return $array;
}

Here is my code in my .tpl file

Problems: 
<select name="problems[]" multiple="multiple">
    <option value="">Select Problems</option>
    {foreach from=$problems key=id item=name}
        {$newArray|push:$id}
        <option value="{$id}">{$name}</option>
    {/foreach}
</select>
{$newArray}

Problem: My dropdown consists of about 20 elements so $newArray should have about 20 id's in it but when I check $newArray, it is empty. So it seems that it never gets assigned back to the template after the modifier runs.

I know that I can use {assign var=newArray} in my .tpl file beforehand but I'm hoping that there is a way of assigning new variables from within a modifier function. I also know it's possible from a function plugin because it gets passed the $smarty variable, but I just want to know specifically, How I can make this work using a modifier plugin?

Aust
  • 11,552
  • 13
  • 44
  • 74
  • 1
    what is your end goal for this? you can just iterate over the options list in javascript with a .each function and access all of the ids. or you can just save the array of just the ids in the php before you call the template at all. – nathan hayfield Oct 16 '12 at 15:43
  • @nathanhayfield - `$problems` is dynamic so I don't know what it looks like until this point in my code. Yes I could use JavaScript but since I'm already using Smarty it would be cleaner code and more convenient to do it all in Smarty so I thought I'd ask and find out. – Aust Oct 16 '12 at 15:50

2 Answers2

0

There is some code posted on the SMARTY FORUM that might help you out. Other people have pointed out that it is a way for you to do what you need but its a little complicated and is not guaranteed to work when new updates come out. Hope it helps you out though. Cheers.

nathan hayfield
  • 2,627
  • 1
  • 17
  • 28
0

Try to push "&" before $array variable like that

function smarty_modifier_push(& $array, $push){
    if(!isset($array)){
        $array = array($push);
    }elseif(is_array($array)){
        $array[] = $push;
    }
    return $array;
}
Hắc Huyền Minh
  • 1,025
  • 10
  • 13