Skip to content

Instantly share code, notes, and snippets.

@hack3rvaillant
Last active April 19, 2021 13:10
Show Gist options
  • Save hack3rvaillant/1ce2e4c41b4a9585548c7bbc86305d1b to your computer and use it in GitHub Desktop.
Save hack3rvaillant/1ce2e4c41b4a9585548c7bbc86305d1b to your computer and use it in GitHub Desktop.
module FormsHelper
def yala_form_with(**options, &block)
form_with(**options.merge(builder: YalaFormBuilder), &block)
end
end
<%= yala_form_with model: @community_and_admin, url: communities_path, scope: :community, class: "form flex flex-col max-w-xl mx-auto" do |f| %>
<%= f.labelled_text_field :name, class: "input", placeholder: "Oasis Learning", label: 'Name' %>
<%= f.labelled_text_field :slug, class: "input", placeholder: "oasis-learning", label: 'Slug' %>
<%= f.labelled_text_field :username, class: "input", placeholder: "keziah82", label: 'Username' %>
<%= f.labelled_email_field :email, class: "input", placeholder: "[email protected]", label: 'Email' %>
<%= f.labelled_password_field :password, class: "input", placeholder: "*********", label: 'Password' %>
<%= f.submit 'Create', class: "btn-success my-4" %>
<% end %>
# frozen_string_literal: true
class YalaFormBuilder < ActionView::Helpers::FormBuilder
ERROR_CLASS = "error"
def labelled_text_field(attribute, args = {})
@template.content_tag(:div, class: "form-group") do
label(attribute, args[:label], class: "label") +
text_field(attribute, merge_args(attribute, args)) +
display_errors(attribute)
end
end
def labelled_email_field(attribute, args = {})
@template.content_tag(:div, class: "form-group") do
label(attribute, args[:label], class: "label") +
email_field(attribute, merge_args(attribute, args)) +
display_errors(attribute)
end
end
def labelled_password_field(attribute, args = {})
@template.content_tag(:div, class: "form-group") do
label(attribute, args[:label], class: "label") +
password_field(attribute, merge_args(attribute, args)) +
display_errors(attribute)
end
end
private
def display_errors(attribute)
return unless any_errors?(attribute)
@template.content_tag(:div, class: "errors-list") do
errors(attribute).collect do |error|
@template.content_tag(:div, error.message)
end.join.html_safe
end
end
def errors(attribute)
object.errors.select { |err| err.attribute == attribute }
end
def any_errors?(attribute)
errors(attribute).any?
end
def merge_error_class(attribute, args)
return args[:class] unless any_errors?(attribute)
"#{ERROR_CLASS} #{args[:class]}"
end
def merge_args(attribute, args)
args.merge!({class: merge_error_class(attribute, args)})
end
end
@hack3rvaillant
Copy link
Author

Screenshot 2021-04-19 at 15 09 20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment