浏览代码

Handle date in teacher form

Andrea Fazzi 6 年之前
父节点
当前提交
54421b5c96
共有 2 个文件被更改,包括 21 次插入4 次删除
  1. 18 1
      renderer/renderer.go
  2. 3 3
      templates/teachers_add_update.html.tpl

+ 18 - 1
renderer/renderer.go

@@ -4,6 +4,7 @@ import (
 	"encoding/json"
 	"fmt"
 	"html/template"
+	"log"
 	"mime"
 	"net/http"
 	"net/url"
@@ -11,6 +12,7 @@ import (
 	"path/filepath"
 	"reflect"
 	"strings"
+	"time"
 
 	"github.com/gocarina/gocsv"
 	"github.com/gorilla/schema"
@@ -38,7 +40,8 @@ var (
 	Render       map[string]func(http.ResponseWriter, *http.Request, interface{}, ...url.Values)
 
 	funcMap = template.FuncMap{
-		"query": query,
+		"query":       query,
+		"convertDate": convertDate,
 	}
 
 	contentTypeToFormat = map[string]string{
@@ -96,6 +99,10 @@ func query(values ...string) template.URL {
 	return template.URL(urlValues.Encode())
 }
 
+func convertDate(t time.Time) string {
+	return fmt.Sprintf("%d-%02d-%02d", t.Year(), t.Month(), t.Day())
+}
+
 // FIXME: Not safe. We should check if it responds to the error interface instead.
 func isErrorType(data interface{}) bool {
 	return strings.Contains(strings.ToLower(reflect.TypeOf(data).String()), "error")
@@ -250,11 +257,21 @@ func Decode(dst interface{}, r *http.Request) error {
 	switch GetContentFormat(r) {
 
 	case "html":
+		var timeConverter = func(value string) reflect.Value {
+			if v, err := time.Parse("2006-01-02", value); err == nil {
+				return reflect.ValueOf(v)
+			}
+			return reflect.Value{}
+		}
+
 		if err := r.ParseForm(); err != nil {
 			return err
 		}
 
 		decoder := schema.NewDecoder()
+		decoder.RegisterConverter(time.Time{}, timeConverter)
+
+		log.Println(r.PostForm)
 		if err := decoder.Decode(dst, r.PostForm); err != nil {
 			return err
 		}

+ 3 - 3
templates/teachers_add_update.html.tpl

@@ -60,11 +60,11 @@
     <div class="form-row">
       <div class="col">
 	<label class="control-label" for="teacher_date_from">In servizio dal</label>
-	<input type="date" name="DateFrom" class="form-control" id="teacher_date_from" {{if .Options.Get "update"}} value="{{.Data.DateFrom}}" {{end}}>
+	<input type="date" name="DateFrom" class="form-control" id="teacher_date_from" {{if .Options.Get "update"}} value="{{convertDate .Data.DateFrom}}" {{end}}>
       </div>
       <div class="col">
-	<label class="control-label" for="teacher_date_from">In servizio fino al</label>
-	<input type="date" name="DateTo" class="form-control" id="teacher_date_to" {{if .Options.Get "update"}} value="{{.Data.DateTo}}" {{end}}>
+	<label class="control-label" for="teacher_date_to">In servizio fino al</label>
+	<input type="date" name="DateTo" class="form-control" id="teacher_date_to" {{if .Options.Get "update"}} value="{{convertDate .Data.DateTo}}" {{end}}>
       </div>
     </div>