2

I'm building my very first web app, and I am having a hard time accessing individual fields of a form when the user submits the form. Here's what I have:

(defroutes app
  (GET "/" [] homepage)
  (POST "/city" request display-city)
  (route/resources "/")
  (route/not-found "Not Found"))


(defn display-city [request]
  (html5
     [:div {:class "the-city"}
      [:h2 "ALL ABOUT YOUR CITY"]
      [:ul
       [:li "Your city is " (str request) "! That's all"]]]))

;; and here's the hiccup form:
   [:form {:action "/city" :method "post"}
    (anti-forgery-field)
    [:p "Enter your home address"]
    [:div
     [:label {:for "street-field"} "Street:"]
     [:input {:id "street-field"
              :type "text"
              :name "street"}]]
    [:div
     [:label {:for "city-field"} "City:"]
     [:input {:id "city-field"
              :type "text"
              :name "city"}]
    [:div
     [:label {:for "state-field"} "State:"]
     [:input {:id "state-field"
              :type "text"
              :name "state"}]
     [:label {:for "zip-field"} "ZIP:"]
     [:input {:id "zip-field"
              :type "text"
              :name "zip"
              :size "10"}]]
    [:div.button
     [:button {:type "submit"} "Submit"]]]])

;; When I run the code above, I can see the entire form that's submitted via (str request), in what looks to be a Clojure map. But I can't figure out how to extract individual "key/vals" (from that address form, I'd like to extract the city), or how to store those results in a way that I can use it. Any ideas?

This is a super basic /city page that I am trying to get running to understand how things work before building bigger things. Thanks!

  • I don't understand the question. What is "city"? Pls show an example of input data, output data, what you've tried, & what happened. – Alan Thompson May 08 '18 at 06:29

1 Answers1

4

In your request map, there should be a key :form-params with a map of key/value pairs that were POSTed. Here's how you could get an individual value out:

(get-in request [:form-params :city])

Or you could destructure :form-params map to bind many values at once:

(let [{:keys [city state zip]} (:form-params request)]
  (format "%s, %s %s" city state zip))
Taylor Wood
  • 15,886
  • 1
  • 20
  • 37
  • Thank you! When I use the `(get-in)` form, it's telling me that it is: `Unable to resolve symbol: param-city in this context` within a `let` clause. Can you tell what I'm doing wrong? (let [param-city (get-in request [:form-params :city] .....)] – orangeorangepeel May 08 '18 at 16:30
  • hmm it's returning an empty string, would you know what could cause that? – orangeorangepeel May 08 '18 at 17:08