From b9a6d6d5e1b74b9698f70e97db1e4a379d72a12d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Davi=20Tapaj=C3=B3s?= <54637230+davi-tapajos-codeminer42@users.noreply.github.com> Date: Sat, 25 Jan 2020 11:42:37 -0300 Subject: [PATCH] Expose required fields on form (#1521) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Displays an asterisk beside label on form when field is required Issue: https://github.com/thoughtbot/administrate/issues/1489 ![Captura de Tela 2020-01-09 às 17 20 38](https://user-images.githubusercontent.com/54637230/72172195-55363580-33b3-11ea-8475-edb4520b276d.png) --- .../administrate/components/_field-unit.scss | 7 +++++ .../administrate/application_helper.rb | 19 +++++++++++++ .../administrate/application/_form.html.erb | 2 +- .../administrate/application_helper_spec.rb | 28 +++++++++++++++++++ 4 files changed, 55 insertions(+), 1 deletion(-) diff --git a/app/assets/stylesheets/administrate/components/_field-unit.scss b/app/assets/stylesheets/administrate/components/_field-unit.scss index 0908bd4435..d5858ae6a9 100644 --- a/app/assets/stylesheets/administrate/components/_field-unit.scss +++ b/app/assets/stylesheets/administrate/components/_field-unit.scss @@ -34,3 +34,10 @@ width: calc(25% - 1rem); } } + +.field-unit--required { + label::after { + color: $red; + content: " *"; + } +} diff --git a/app/helpers/administrate/application_helper.rb b/app/helpers/administrate/application_helper.rb index c51a3b8670..fa0a196761 100644 --- a/app/helpers/administrate/application_helper.rb +++ b/app/helpers/administrate/application_helper.rb @@ -15,6 +15,25 @@ def render_field(field, locals = {}) render locals: locals, partial: field.to_partial_path end + def requireness(field) + required_field?(field) ? "required" : "optional" + end + + def required_field?(field) + has_presence_validator?(field.resource.class, field.attribute) + end + + def has_presence_validator?(resource_class, field_name) + validators_on(resource_class, field_name). + any? { |v| v.class == ActiveRecord::Validations::PresenceValidator } + end + + def validators_on(resource_class, field_name) + return [] unless resource_class.respond_to?(:validators_on) + + resource_class.validators_on(field_name) + end + def class_from_resource(resource_name) resource_name.to_s.classify.constantize end diff --git a/app/views/administrate/application/_form.html.erb b/app/views/administrate/application/_form.html.erb index 23d8024162..c380e23b43 100644 --- a/app/views/administrate/application/_form.html.erb +++ b/app/views/administrate/application/_form.html.erb @@ -34,7 +34,7 @@ and renders all form fields for a resource's editable attributes. <% end %> <% page.attributes.each do |attribute| -%> -