1
votes

I'm using codeigniter with Twig - i'm trying to create a dynamic select boxes which consist of data from data base.

Here is what i'm doing now

      // animals is $data['animals']=$this->loadmodel->some_function()
      // animals passed from the controller ...


           <select  id="foo" class="form-control">
                <option selected="true" >Animals</option>
                   {%  for animal_key in animals %}
                      <option >
                     {{ animal_key ["animal_description"] }}
                     </option>
                   {% endfor %}
             </select>

So all above is working well. But what if i want to make it dynamic? each select box get data from different method in the controller - suppose i have data from other method - like here

       // orders is $data['orders']=$this->loadmodel->some_function()
       // orders passed from the controller ...

           <select  id="foo" class="form-control">
                <option selected="true" >orders</option>
                   {%  for order_key in orders%}
                      <option >
                     {{ order_key ["order_description"] }}
                     </option>
                   {% endfor %}
             </select>

             <select  id="foo" class="form-control">
                <option selected="true" >Animals</option>
                   {%  for animal_key in animals %}
                      <option >
                     {{ animal_key ["animal_description"] }}
                     </option>
                   {% endfor %}
             </select>

What i had in mind was to do something like this :

Set an array of the controller's names :

         {% set controller_names = ['animals','orders']%}

Set an array of the controllers variables a nd their keys :

         {% set controller_vars = 
           ['animals'=>'animal_description','orders'=>'order_description']%}

Then iterate over it like that

         {%  for names in controller_names  %}
              <select  id="foo" class="form-control">
                <option selected="true" >{{ name }}</option>
                   {%  for controller_key in controller_vars %}
                      <option >
                     {{ controller_vars [ controller_key] }} //suppose to be Twig variables
                     </option>
                   {% endfor %}
             </select>
         {% endfor %} 

So what i need is the convert the set controller_vars array to Twig variables (as long as it possible).....

1

1 Answers

0
votes

You can use the attribute function:

               {%  for controller_key in controller_vars %}
                  <option >
                    {{ attribute(controller_key, controller_vars) }}
                 </option>
               {% endfor %}

Hope this help