class Kemal::Form

Overview

Kemal::Form contains classes and macros that makes working with forms in your Kemal application fun and easy.

require "kemal"
require "kemal-form"

class LoginForm < Kemal::Form
  field username : Kemal::Form::TextField,
                     validators: [Kemal::FormValidator::Required.new]
  field password : Kemal::Form::PasswordField,
                     validators: [
                       Kemal::FormValidator::Length.new(min: 6)
                     ]
  button login : Kemal::Form::SubmitButton,
                   text: "Login"
end

get "/login" do
  form = LoginForm.new
  render "src/views/login.ecr"
end

post "/login" do |env|
  form = LoginForm.new env
  if form.valid?
    puts "You are now logged in"
    env.redirect "/"
    next
  end
  render "src/views/login.ecr"
end

Defined in:

kemal-form.cr
kemal-form/buttons.cr
kemal-form/errors.cr
kemal-form/field.cr
kemal-form/fields/common.cr
kemal-form/fields/select.cr
kemal-form/fields/textarea.cr
kemal-form/form.cr
kemal-form/label.cr

Constant Summary

VERSION = "0.4.0"

Constructors

Instance Method Summary

Constructor Detail

def self.new(ctx : Nil | HTTP::Server::Context = nil) #

Initializes a new form.

class MyForm < Kemal::Form
end

get "/" do
  form = MyForm.new
  render "src/views/index.ecr"
end

post "/" do |env|
  form = MyForm.new env
  # ...
  render "src/views/index.ecr"

[View source]

Instance Method Detail

def add_error(message : String) #

Adds error to the form.

post "/login" do |env|
  form = LoginForm.new env
  form.valid?
    if wrong_password_entered
      form.add_error "Invalid username or password"
      ...
    end
    ...
  end
  ...
end

[View source]
def body : URI::Params #

Returns the form body.

NOTE This is the same as env.params.body.


[View source]
def buttons : Array(Button) #

Returns the form's buttons.


[View source]
def errors : Array(String) #

Returns form errors.


[View source]
def fields : Array(Field) #

Returns the form's fields.


[View source]
def valid? : Bool #

Returns true if the form is valid, false otherwise.

class MyForm < Kemal::Form
end

post "/" do |env|
  form = MyForm.new env
  if form.valid?
    puts "form is valid"
    env.redirect "/"
    next
  end
  render "src/views/index.ecr"
end

[View source]