简体   繁体   中英

How to handle dynamic number of inputs from html form with with Revel Golang

I have an html form with dynamic number of inputs. Each input must be a Model object, and i also have a function, which receives values from this inputs. My html form:

<form action="{{url "Votes.CreateVote"}}" id="formVoteCreate" method="POST">
            <p class="field">
                <label>Question:</label>
                <input type="text" name="question" size="40"  />
            </p>
             <div ng-repeat="answer in answers">
                <p class="field">
                    <label>//stuff.title//:</label>
                    <input type="text" name=//stuff.name// size="40"  />
                </p>
             </div>
            <p>
                <input ng-click="addInput()" class="btn"  type="button" value="Add answer">
            </p>
            <p class="buttons">
                <input class="btn" type="submit" value="Create" />
            </p>
        </form>

And revel golang handler:

func (c Votes) CreateVote() revel.Result {
   // in this place i want get a slice with answers from html form
   return c.Redirect(routes.App.Index())
}

and answer model:

type Answer struct {
  Model
  Text    string
}

How can i send form's values as a slice with answers packed to Model?

Each Revel controller comes with an attached Request , which is really just a normal Go standard library Request . As such, this is the same as for plain Go web servers, in that we cannot use the Request.Form.Get("inputname") method, as this would only give the first result. Instead, we need to access the values in the Form map directly:

package controllers

import (
    "log"

    "github.com/robfig/revel"
)

type App struct {
    *revel.Controller
}

func (c App) Index() revel.Result {
    if err := c.Request.ParseForm(); err != nil {
        // handle error
    }
    values := c.Request.Form["text"]
    for i := range values {
        log.Println(values[i])
    }
    return c.Render()
}

The example above is for a simple application like the one generated by Revel when you start a project, with an input named text , and can be adapted to your specific case.

The values variable is of type []string , which is why the following is logged, if you submit a GET request with query string ?text=value1&text=value2&text=value3 , as would happen for a form with method="GET" and three text inputs with name="text" :

2016/03/07 22:16:41 app.go:19: value1
2016/03/07 22:16:41 app.go:19: value2
2016/03/07 22:16:41 app.go:19: value3

The form in the question happens to use method POST, but the code for reading the values from the form remains the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM