Skip to content

Commit

Permalink
core,formular: add make-checkboxes and required/list
Browse files Browse the repository at this point in the history
  • Loading branch information
Bogdanp committed Mar 1, 2024
1 parent 0f158eb commit 2106d71
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
46 changes: 46 additions & 0 deletions congame-core/components/formular.rkt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
input-text
input-time
textarea
make-checkboxes
make-radios)

(define (kwd->symbol kwd)
Expand Down Expand Up @@ -528,6 +529,50 @@
,@((widget-errors) name value errors)))
elt))]))

(define ((required/list [message "You must select one or more items."]) xs)
(if (and xs
(pair? xs)
(not (null? xs)))
(ok xs)
(err message)))

(define ((make-checkboxes options
render-proc
#:required? [required? #t]
#:validators [validators null]
#:attributes [attributes null]) meth)
(match meth
['validator
(apply ensure
binding/list
(cond
[(string? required) (cons (required/list required) validators)]
[required? (cons (required/list) validators)]
[else validators]))]

['widget
(lambda (name value errors)
(define (make-checkbox option [label ""])
(define the-values
(and value
(for/list ([bind (in-list (if (pair? value) value (list value)))])
(string->symbol (bytes->string/utf-8 (binding:form-value bind))))))
(define attributes*
(if (and the-values (memq option the-values))
(cons '(checked "") attributes)
attributes))
`(label
(input
([name ,name]
[type "checkbox"]
[value ,(symbol->string option)]
,@attributes*))
,label))
(haml
(.group
(render-proc options make-checkbox)
,@((widget-errors) name value errors))))]))

(define ((make-radios options
render-proc
#:required? [required? #t]
Expand Down Expand Up @@ -557,6 +602,7 @@
(render-proc options make-radio)
,@((widget-errors) name value errors))))]))


;; help ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(define (cons/required? required? l)
Expand Down
16 changes: 14 additions & 2 deletions congame-example-study/conscript-form.rkt
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,25 @@
@button{Continue}})

(defstep (the-form)
(define (on-submit #:name n #:text t)
(eprintf "name: ~s text: ~s~n" n t))
(define (on-submit #:name n #:text t #:checkboxes cs)
(eprintf "name: ~s text: ~s checkboxes: ~s~n" n t cs))

(define options
'((a . "Option a")
(b . "Option b")))
(define (render-checkboxes options render-checkbox)
`(div
()
,@(for/list ([o (in-list options)])
(define v (car o))
(define l (cdr o))
(render-checkbox v l))))

@html{@h1{The Form}
@form[#:action on-submit]{
@label{Name: @input-text[#:name] @~error[#:name]}
@textarea[#:text]{Content:}
@binding[#:checkboxes @make-checkboxes[options render-checkboxes]]
@submit-button}})

(defstep (end)
Expand Down

0 comments on commit 2106d71

Please sign in to comment.