Created
February 6, 2024 04:47
-
-
Save georgekettle/a43ca56d03627a871a593143192d7261 to your computer and use it in GitHub Desktop.
PhlexUI::Form::Builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module PhlexUI | |
class Form::Builder < Base | |
# include Phlex::Rails::Helpers::FormAuthenticityToken | |
def initialize(model: nil, scope: nil, url: nil, format: nil, method: :post, **attrs) | |
@object = model | |
@scope = scope | |
@url = url | |
@format = format | |
@method = method | |
super(**attrs) | |
end | |
def template(&block) | |
render PhlexUI::Form.new(action: form_url, method: form_method, **attrs) do | |
# Authenticity token hidden input | |
# render PhlexUI::Form::Input.new(type: :hidden, name: :authenticity_token, value: helper.form_authenticity_token) if helper.form_authenticity_token | |
render PhlexUI::Form::Spacer.new do | |
block.call | |
end | |
end | |
end | |
def input(name, label: nil, hint: false, error: nil, **input_attrs) | |
name = name.to_s | |
scoped_name = @scope ? "#{@scope}[#{name}]" : name | |
label ||= convert_name_to_label(name) | |
error = @object.errors[name].first if @object && @object.errors[name].present? | |
render PhlexUI::Form::Item.new do | |
render PhlexUI::Label.new(for: scoped_name) { label } if label | |
render PhlexUI::Input.new(name: scoped_name, id: scoped_name, error: error, **input_attrs) | |
render PhlexUI::Hint.new { hint } if hint | |
end | |
end | |
def submit(type: :submit, **button_attrs, &block) | |
render PhlexUI::Button.new(type!: type, **button_attrs, &block) | |
end | |
private | |
def form_method | |
@object ? (@object.new_record? ? :post : :patch) : @method | |
end | |
def form_url | |
if @url | |
@url | |
elsif @object | |
url_from_object | |
else | |
raise "No URL provided" | |
end | |
end | |
def url_from_object | |
base_url = @object.new_record? ? "/#{@object.class.name.downcase.pluralize}" : "/#{@object.class.name.downcase.pluralize}/#{@object.id}" | |
@format ? "#{base_url}.#{@format}" : base_url | |
end | |
def convert_name_to_label(name) | |
name.to_s.split("_").map(&:capitalize).join(" ") | |
end | |
def default_attrs | |
{} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment