Пример #1
0
func editQuestion(w http.ResponseWriter, r *http.Request) error {
	vars := mux.Vars(r)
	questionId, _ := strconv.ParseInt(vars["id"], 10, 64)
	question, err := LoadQuestion(int(questionId))
	if err != nil {
		return err
	}

	r.ParseForm()

	form := NewQuestionForm(r, question)
	fmt.Println(forms.DecodeForm(form, r.Form))

	errors := forms.Validate(form)
	if len(errors) > 0 {
		context.Set(r, "editQuestionForm", form)
		editQuestionForm(w, r)
		return nil
	}

	form.scan(question)
	err = question.Save()
	if err != nil {
		return err
	}

	err = question.SetSubjectTypes(form.subjectTypeIds())
	if err != nil {
		return err
	}

	web.FlashSuccess(r, fmt.Sprintf("\"%v\" has been saved", question.Name))
	http.Redirect(w, r, fmt.Sprintf("/admin/questions/%v", question.Id), http.StatusFound)
	return nil
}
Пример #2
0
func addQuestion(w http.ResponseWriter, r *http.Request) error {
	vars := mux.Vars(r)
	questionType, ok := types.QuestionTypes[vars["questionType"]]
	if !ok {
		return fmt.Errorf("Question Type %v does not exist", vars["questionType"])
	}

	question := &Question{Type: questionType.Name()}

	var form = NewQuestionForm(r, question)
	r.ParseForm()
	err := forms.DecodeForm(form, r.Form)

	if err != nil {
		web.FlashWarning(r, err.Error())
	}

	if !web.ValidateCSRF(r, form.CSRF) {
		return fmt.Errorf("Invalid token")
	}

	validationErrors := forms.Validate(form)

	if len(validationErrors) == 0 {

		q := new(Question)
		q.Type = questionType.Name()
		form.scan(q)
		q.Save()

		q.SetSubjectTypes(form.subjectTypeIds())

		web.FlashSuccess(r, fmt.Sprintf("\"%v\" created successfully.", q.Name))

		http.Redirect(w, r, "/admin/questions", http.StatusFound)
		return nil
	} else {
		context.Set(r, "newQuestionForm", form)
		return addQuestionForm(w, r)
	}
	return nil
}