Indy Forms
Forms can be simplified using IndyForm. A form can be implemented in just couple of lines.
use IndyForm.FormComponent, context: Context
form_component(form_key, create_action, update_action, opts)
-
form_key
: is your schema name. This is used for finding the form in the params. -
create_action
: can be anatom
orlist of atoms
. This is used to determine what action should be performed - create or update. -
update_action
: can be anatom
orlist of atoms
. This is used to determine what action should be performed - create or update.
create_action
orupdate_action
values can be directly mapped to socket.assigns.live_action values. -
opts
:change_listeners
can be enabled throughopts
form_component(form_key, create_action, update_action, change_listeners: true)
Example
A complete example which reduces around 50 lines of boilerplate code form component
to 3 just lines:
defmodule UserForm do
alias IndyFormSample.Accounts, as: Context
use IndyForm.FormComponent, context: Context
form_component("user", :new, :edit)
end
or can be writen in verbose 7 lines if you prefer this way:
defmodule UserForm do
alias IndyFormSample.Accounts, as: Context
use IndyForm.FormComponent, context: Context
@form_key "user"
@create_action :new
@edit_action :edit
form_component(@form_key, @create_action, @edit_action)
end
Value Change Listeners
on_value_change/2
is invoked when there is a change is detected in field while handling validate
event.
key
is an atom - which is field name defined in your form.
You can override to handle changes in form happening without writing a single line of javascript.
Note: Don’t forget to enable value change listeners by passing change_listeners: true
through form_component
opts.
# handle changes relating to field :contact_me
def on_value_change(socket, {:contact_me, _old_value, new_value}) do
show_phone? = show_phone?(new_value)
show_email? = show_email?(new_value)
socket
|> assign(:show_phone, show_phone?)
|> assign(:show_email, show_email?)
end
# needed for handling changes not relating to our fields of interest
def on_value_change(socket, _), do: socket
Design Goals
Design goals of this library :
- less code injection through macros.
- less magic and more explicit configuration.
- flexibility to override everything to perform one off customizations.
- reduce boilerplate code in application.
You can read docs about forms and contexts.
Browse code at GitHub - lkarthee/indy_form: Simplify LiveView Forms.
And browse sample code here - GitHub - lkarthee/indy_form_sample: A sample project using IndyForm
I want hear more from you - please share feedback or discuss about use cases or suggest design changes.
Note: this library is not published on Hex. You can use it from GitHub. I want to publish after hearing your feedback.
Regards
Kartheek
Edits: changed sample code to reflect few changes.