Search code examples
formsclojurehiccup

Clojure (Hiccup): How can I know which submit button got pressed in a form?


I have a form, using hiccup framework. It looks like this:

(form-to {:enctype "multipart/form-data"}
  [:post "/add-data"]

  ...

  (submit-button {:class "btn"} "Save")
  (submit-button {:class "btn} "Clone"))

How do I know which submit button got pressed, without using jQuery/javascript?

I looked at the Hiccup's documentation for request. But, the request element does not have a lot of documentation.


Solution

  • A complete example looks like:

    (ns myapp.routes.home
      (:use [hiccup core form])
      (:require [compojure.core :refer :all]))
    
    (defn quick-form [& [name message error]]   
      (html
       (form-to {:enctype "multipart/form-data"}
        [:post "/form-out"]
       (text-field "Hello")
       (submit-button {:class "btn" :name "submit"} "Save")
       (submit-button {:class "btn" :name "submit"} "Clone"))))
    

    Note that using the same name for both submit buttons allows you to do a simple lookup of the "submit" key in the result map.

    (defroutes home-routes
     (GET "/form-in" [] (quick-form))
     (POST "/form-out" [:as request] (str (request :multipart-params))))
    

    When opening the following page:

     http://localhost:3000/form-in
    

    And filling the form, the result out of the POST route is:

     {"submit" "Save", "Hello" "hello2"}
    

    By the way, I found an old useful post about the way the request map is structured in Compojure, so it makes it easier to destructure it in the Clojure code.