Custom validation context is missing
Opened this issue · 6 comments
Required labels missing when model has specific validation context, different from save update create.
As result, such validators are skipped. I think there should be some context option for semantic_form_for
What validation context? Could you give an example of how that should work? Links to Rails documentation?
What validation context? Could you give an example of how that should work? Links to Rails documentation?
https://guides.rubyonrails.org/active_record_validations.html#on
When rendering form, fields that has presence validators with :on option, are displayed without required label.
(
validator_on.exclude?(:save)) && ( # there is no on: :save
(object.new_record? && validator_on.exclude?(:create)) # it is new record and there is no on :create
||
(!object.new_record? && validator_on.exclude?(:update) # it is existing object and there is no :update
)
)
I see the logic as sound.
And I see it tested.
formtastic/spec/inputs/base/validations_spec.rb
Lines 63 to 223 in 69a01f0
If it is not working for your case please try to contribute some example or a test case that shows what is wrong.
I just stumbled upon the same thing. My case is that I have a User
model with a multi-step onboarding wizard where I validate the fields based on the current step the user is in. There are multiple edit views for the user that split up form fields by their logic (e. g. address, profile information).
# Contextual validations for step 1 in form wizard.
with_options on: %i[basic_information create] do
validates :name, presence: true
validates :country, presence: true, country: true
end
# Contextual validations for edit profile action.
with_options on: %i[edit_profile] do
validates :name, presence: true
end
This will render the name
field in a form as "optional" because the context is missing. Of course it can be circumvented by manually putting required: true
to those fields but the magic is lost then.
Ok, and how would you want the form to look like?
semantic_form_for user, validation_context: :basic_information do |f|
Or do it per input? Or for some inputs at ones?
I think this could make sense if done properly, so it also makes it easier for you to hook into determining what is required.
Maybe extracting the this:
formtastic/lib/formtastic/inputs/base/validations.rb
Lines 136 to 151 in 69a01f0
Into a method that is easily overridable in your custom form builder.
Just stumbled into wanting this myself. Yes, the example syntax floated above by @mikz seems like it'd be great.