How to dynamically add input elements to form?


I have a form which needs to add 3 fields dynamically.
The fields are for recipe ingredients, and look like this currently.

               // eg: 1
                $form->addText('ingredients_number', 'Ingredients number:')
                        ->setRequired('Please enter a description of this recipe.')
                        ->setHtmlAttribute('value', '1')
                        ->addRule(Form::MIN_LENGTH, 'Number must be at least %d', 1);

                // eg: kg
                $res = $this->db->table('recipe_measure')->fetchPairs('id', 'name');
                $form->addSelect('recipe_measure_id', 'Measure:', $res)
                        ->setRequired('Please Select an option for Measure.');

                // eg: tomatoes
                $form->addText('ingredients', 'Ingredients:')
                        ->setRequired('Please enter Ingredients.')
                        ->setHtmlAttribute('id', 'hint')
                        ->addRule(Form::MIN_LENGTH, 'Ingredient must be at least %d long', 2);


This works as expected in the template like this

  <div class="row">
    <div class="large-4 columns">
      <label n:name=ingredients_number>Number</label>
        <input n:name=ingredients_number>

    <div class="large-4 columns">
      <label n:name=recipe_measure_id>Measure</label>
        <select n:name=recipe_measure_id></select>

    <div class="large-4 columns">
      <label n:name=ingredients>Ingredients</label>
        <input n:name=ingredients>
  </div> <!-- end row -->

Of course, having a single ingredient, is basically, eating an apple, and most recipes call for varying amounts of ingredients.

How can I add a new row to for a new ingredient using the presenter?
I can do this with just jquery, and hard coding the fields into the javascript, that somehow seems dirty.

$(document).ready(function() {
    var max_fields = 10;
    var wrapper = $(".container1");
    var add_button = $(".add_form_field");

    var x = 1;
    $(add_button).click(function(e) {
        if (x < max_fields) {
            $(wrapper).append('<div class="row"><a href="#" class="delete">Delete</a><div class="large-4 columns"><input type="text" name="number[]"/></div><div class="large-4 columns"><input type="text" name="measure[]"/></div><divclass="large-4 columns"><input type="text" name="ingredient[]"/></div>'); //add input box
        } else {
            alert('Maximum number of fields reached')

    $(wrapper).on("click", ".delete", function(e) {
Marek Bartoš
Nette Blogger | 1212

You may use a multiplier…s-multiplier


Mabar wrote:

You may use a multiplier…s-multiplier

Wow. That's a lot of code to generate a form field.