Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support handling empty arrays in form schemas #102

Closed
timriley opened this issue Apr 11, 2016 · 3 comments
Closed

Support handling empty arrays in form schemas #102

timriley opened this issue Apr 11, 2016 · 3 comments
Labels

Comments

@timriley
Copy link
Member

In HTML forms it seems there’s no way to properly submit an empty array. So instead of some blank value being submitted with the key, it just doesn’t get submitted at all. And unlike checkboxes with the hidden input you can place above them to ensure a default “off” value is submitted, with arrays there seem to be no such workarounds.

For our app, this is the best I could come up with for a schema where you really do want the array’s key to be present, so its nested validations can run:

schema = Dry::Validation.Form do
  key(:contributors).each do
    schema do
      key(:contributor_id).required(:int?)
    end
  end

  configure do
    def call(input)
      input = input.dup
      input["contributors"] = [] unless input.key?("contributors")

      super(input)
    end
  end
end

input = {}
result = schema.(input)
# => #<Dry::Validation::Result output={:contributors=>[]} messages={}>

It would be nice if we could somehow support this kind of use case a little bit better with the form schemas.

@solnic solnic added the feature label Apr 12, 2016
@solnic
Copy link
Member

solnic commented Apr 12, 2016

This will be solved once we have support for types with default values. Then we can tweak Form::Array to be a default-value type having [] as the fallback value when nil was passed.

@timriley
Copy link
Member Author

This sounds good. For our usage (which I think is a fairly reasonable approach for handling empty arrays in forms), I think we'd need dry-rb/dry-types#76 to be in place alongside this.

@timriley timriley changed the title Somehow support handling missing keys for empty array values in form schemas? Support handling empty arrays in form schemas Apr 13, 2016
@solnic
Copy link
Member

solnic commented Jul 1, 2016

Closing this one since all pieces are done

@solnic solnic closed this as completed Jul 1, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants