Search code examples
odooodoo-8qweb

dynamic variable qweb odoo v8


I have a web page where I need to create a number of fields and variables dynamically.

Let me explain : On page One, I have a text field where i have to type the number of users I want. That number is passed as parameter to the next page (post method) and collected as nb_user on page Two.

In the template.xml of page Two i have this code :

  <form method="POST" class="col-md-8" action="/page_three">


  <t t-foreach="nb_user" t-as="user">
    <input type="text" name="comp_1_user_1" id="comp_1_user_1" class="form-control" placeholder="Computer user"/>

   </t>


<input type="submit" class="btn btn-primary" value="Validate"/>

What I would like is that based on the number that is passed in post (nb_user), it should dynamically create that amount of text fields ans also create unique id (comp_1_user_1, comp_1_user_2 etc....) so that i can enter that data into my database.

So if the parameter was 3 then it should create 3 text fields and create 3 variables comp_1_user_1, comp_1_user_2, comp_1_user_3.

I hope I was clear enough . I am very new to Odoo and Qweb.

Thanks for any help you can provide.


Solution

  • To mix literals with non-literals, use the tf-attf-$name attribute where $name stands for the attribute needed. As parameter you can then use a format-string, in your case:

    <t t-foreach="nb_user" t-as="user">
        <input type="text" 
               t-attf-name="comp_1_user_{{ user }}"
               t-attf-id="comp_1_user_{{ user }}" 
               class="form-control" 
               placeholder="Computer user"/>
    </t>
    

    This will be evaluated by QWeb to be the attribute name (and id respectively) with the contents evaluated as a format string. That is, the string comp1_user_ is passed as it is and the contents of the {{ user }} snippet is evaluated as Python code.

    Run with an array containing [1,2,3] instead of nb_user like so

    <t t-foreach="[1,2,3]" t-as="user">
        <input type="text" 
        t-attf-name="comp_1_user_{{ user }}" 
        t-attf-id="comp_1_user_{{ user }}"
        class="form-control" 
        placeholder="Computer user"/>
    </t>
    

    leads to

    enter image description here

    with name and id iterating over comp_1_user_1, comp_1_user_2 and comp_1_user_3. Screenshot from Chrome DevTools:

    enter image description here

    For more information see docs.