rails_ajax_formhandler 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: a299fae46deed71657ddd8d96ab542fa7eedb2ca
4
+ data.tar.gz: 401ac99e6507a57a31100255f2c66da3d05f900c
5
+ SHA512:
6
+ metadata.gz: 1711b334fe66fc58bb3ca7d3200a671742b3578ffb44d3647ec50692c3ccf93933effdd9284aa22cea3338a31e11a5c766d67480cf193eda65047e28c060aee6
7
+ data.tar.gz: ed4f4479dfd08e6ed65487e987a8533df4a5a53d447ebe4da37ce912c18897356b60269b0557b0b49a98dc370ef1c020d284516d82f4e006abb167abcdf1d79c
data/, ADDED
@@ -0,0 +1,35 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'rails_ajax_formhandler/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "rails_ajax_formhandler"
8
+ spec.version = RailsAjaxFormhandler::VERSION
9
+ spec.authors = ["TODO: Write your name"]
10
+ spec.email = ["TODO: Write your email address"]
11
+
12
+ spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.}
13
+ spec.description = %q{TODO: Write a longer description or delete this line.}
14
+ spec.homepage = "TODO: Put your gem's website or public repo URL here."
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against " \
23
+ "public gem pushes."
24
+ end
25
+
26
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
27
+ f.match(%r{^(test|spec|features)/})
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ spec.add_development_dependency "bundler", "~> 1.14"
34
+ spec.add_development_dependency "rake", "~> 10.0"
35
+ end
data/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ <<<<<<< HEAD
11
+ =======
12
+ /.gitignore
13
+ /lib/.DS_Store
14
+ >>>>>>> 9d6f3ee23dfee4cef6f8454363e58dd9d7624de3
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at TODO: Write your email address. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in rails_ajax_formhandler.gemspec
4
+ gemspec
5
+
6
+ gem 'jquery-rails'
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Davide Brancaccio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,217 @@
1
+ # RailsAjaxFormhandler
2
+
3
+ Submits forms remotely with ajax automatically and handles server responded validation errors by adding error-styles and error-messages to each invalid input-field.
4
+
5
+ ![example1](https://raw.githubusercontent.com/brancadavide/rails_ajax_formhandler/master/input_validation_example1.png)
6
+
7
+
8
+
9
+ ![example2](https://raw.githubusercontent.com/brancadavide/rails_ajax_formhandler/master/input_validation_example2.png)
10
+
11
+
12
+
13
+ ## Installation
14
+
15
+ Add this line to your application's Gemfile:
16
+
17
+ ```ruby
18
+ gem 'rails_ajax_formhandler'
19
+ ```
20
+
21
+ And then execute:
22
+
23
+ $ bundle
24
+
25
+ Or install it yourself as:
26
+
27
+ $ gem install rails_ajax_formhandler
28
+
29
+ In your application.js
30
+
31
+ ```javascript
32
+ //=require ajax_formhandler
33
+ ```
34
+
35
+ If you want to use built in validation-styles, add to your application.scss
36
+
37
+ ```css
38
+ @import "ajax_formhandler";
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ This works with standard generated scaffold controllers, models and views seamlessely!
44
+ Just add the following line to your js-file, for example 'client.js':
45
+
46
+ ```javascript
47
+ $(document).ready(function{
48
+
49
+ var form_handler = new FormHandler();
50
+ form_handler.init();
51
+
52
+ });
53
+
54
+ ```
55
+
56
+ ## Global Options
57
+
58
+ "new FormHandler()" accepts an option object as only argument:
59
+
60
+
61
+ ## HTML
62
+
63
+ html
64
+ an object
65
+
66
+ ```javascript
67
+ {
68
+ html:{
69
+ wrapperTag: "div",
70
+ // each input field and label must be wrapped in order to apply the validation-error-markup
71
+ errorClassName: "fh-error-field",
72
+ // default, using the build-in styles
73
+ helpBlockClass: "help-block"
74
+ // default
75
+ },...
76
+ }
77
+ ```
78
+ or, if you're using Bootstrap Version 3
79
+
80
+ ```javascript
81
+ {
82
+ html: "bootstrap3",...
83
+ }
84
+ ```
85
+
86
+ ## Callbacks
87
+
88
+ success
89
+ a function with the with jqXHR as first, the form-object as second and the event as third argument
90
+
91
+
92
+ ```javascript
93
+ { ...
94
+ success: function(xhr, form, event) {
95
+ // what happens after successfull submit
96
+ }
97
+ }
98
+ ```
99
+
100
+
101
+ error
102
+ function with jqXHR as first, the errorThrown(string) as second, the form-object as third and the event as forth argument
103
+
104
+
105
+ ```javascript
106
+ { ...
107
+ error: function(xhr,error, form, event) {
108
+ // any additional actions
109
+ }
110
+ }
111
+ ```
112
+
113
+ send
114
+ function with the event only argument, will be called on submit
115
+
116
+
117
+ ```javascript
118
+ {
119
+ send: function(event) {
120
+ // any additional actions
121
+ }
122
+ }
123
+ ```
124
+
125
+ Example:
126
+
127
+
128
+ ```javascript
129
+ { html: {
130
+ wrapperTag: "div",
131
+ errorClass: "my-error-class",
132
+ helpBlockClass: "my-help-block"
133
+ },
134
+ success: function(xhr, form, event) {
135
+ $("#succes-message").html("Form successfully submitted")
136
+ }
137
+ }
138
+ ```
139
+
140
+
141
+ ## Controller setup
142
+
143
+ ```ruby
144
+ def create
145
+ @client = Client.new(client_params)
146
+ respond_to do |f|
147
+ if @client.save
148
+ f.json { render :show, status: :created}
149
+ else
150
+ f.json { render json: @client.errors, status: :unprocessable_entity }
151
+ end
152
+ end
153
+
154
+ def update
155
+ respond_to do |f|
156
+ if @client.update(client_params)
157
+ f.json { render :show, status: :ok}
158
+ else
159
+ f.json { render json: @client.errors, status: :unprocessable_entity }
160
+ end
161
+
162
+ end
163
+
164
+ ```
165
+
166
+ ## Model
167
+
168
+ Insert your validations in the model and pass your error-messages like:
169
+
170
+
171
+ ```ruby
172
+ validates :firstname, presence: { message: "We need your firstname!"}
173
+
174
+ ```
175
+
176
+ If you're not familiar with, please refer to [guides.rubyonrails](http://guides.rubyonrails.org/active_record_validations.html).
177
+
178
+
179
+ ## Multiple Forms
180
+
181
+ <<<<<<< HEAD
182
+ If you have two or more forms on one page, FormHandler detects them all and sets them up. The passed arguments will be applied to each form. For specific configuration, call the ".config_form()"
183
+ =======
184
+ If you have two or more forms on one page, FormHandler detects them all and sets them up. The passed arguments will be applied to each for. For specific configuration, call the ".config_form()"
185
+ >>>>>>> 9d6f3ee23dfee4cef6f8454363e58dd9d7624de3
186
+ method:
187
+
188
+ ```javascript
189
+
190
+ var form_handler = new FormHandler({ html: "bootstrap3"})
191
+
192
+ // first argument is the modelname
193
+ // do this before you call ".init()"
194
+ form_handler.config_form("client",{
195
+ success: function(xhr,form, event ) {
196
+ // do something special....
197
+ }
198
+ })
199
+
200
+ form_handler.init();
201
+
202
+ ```
203
+ ## Development
204
+
205
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
206
+
207
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
208
+
209
+ ## Contributing
210
+
211
+ Bug reports and pull requests are welcome on GitHub at https://github.com/brancadavide/rails_ajax_formhandler. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
212
+
213
+
214
+ ## License
215
+
216
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
217
+
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "rails_ajax_formhandler"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
Binary file
Binary file
data/lib/.DS_Store ADDED
Binary file
@@ -0,0 +1,3 @@
1
+ module RailsAjaxFormhandler
2
+ VERSION = "0.1.1"
3
+ end
@@ -0,0 +1,9 @@
1
+ require "rails_ajax_formhandler/version"
2
+
3
+ module RailsAjaxFormhandler
4
+ module Rails
5
+ class Engine<::Rails::Engine
6
+
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,33 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'rails_ajax_formhandler/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "rails_ajax_formhandler"
8
+ spec.version = RailsAjaxFormhandler::VERSION
9
+ spec.authors = ["Davide Brancaccio"]
10
+ spec.email = ["info@yield-in.de"]
11
+
12
+ spec.summary = %q{Handling form submissions via ajax and rendering validation-errors automatically}
13
+ spec.description = %q{RailsAjaxFormhandler is a lightweight Javascript-plugin wich submits your form automatically and displays server responded validation-errors by adding styles and error-messages to the invalid input fields. }
14
+ spec.homepage = "https://github.com/brancadavide/rails_ajax_formhandler"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+
20
+
21
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
22
+ f.match(%r{^(test|spec|features)/})
23
+ end
24
+ spec.bindir = "exe"
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ["lib"]
27
+
28
+ spec.add_development_dependency "bundler", "~> 1.14"
29
+ spec.add_development_dependency "rake", "~> 10.0"
30
+ spec.add_development_dependency 'sprockets-rails', '>= 2.1.3'
31
+ spec.add_development_dependency 'jquery-rails', '>= 3.1.0'
32
+
33
+ end
@@ -0,0 +1,409 @@
1
+
2
+
3
+ /*
4
+ Form-Handler by Davide Brancaccio
5
+
6
+ FormHandler submits your form automatically via ajax and handles validation-rendering also by adding error-styles and messages.
7
+ This works without any additional setup with standard-rails scaffold forms and controllers, just by adding validations to the model.
8
+
9
+ Example scaffold 'Client':
10
+
11
+ client.rb:
12
+
13
+ ....
14
+ validates :firstname, presence: { message: "Can't be blank!"}
15
+ validates :firstname, uniqueness: { scope: [:lastname,:phone], message: "Already exists!"}
16
+ ...
17
+
18
+ clients_controller.rb:
19
+
20
+ ....
21
+ if @client.save
22
+ ...
23
+ format.json { render :show, status: :created }
24
+ ...
25
+ else
26
+ ...
27
+ format.json { render json: @client.errors, status: :unprocessable_entity}
28
+
29
+ ...
30
+
31
+ _form.html.erb
32
+
33
+ ...
34
+ <div class="field">
35
+ <%= f.label :firstname, "Firstname" %><br/>
36
+ <%= f.text_field :firstname %>
37
+ </div>
38
+
39
+ In your client.js just add:
40
+
41
+ $(document).ready(function(){
42
+
43
+ var form_handler = new FormHandler();
44
+ form_handler.init();
45
+
46
+ });
47
+
48
+
49
+ That's it! Now the form will be submited via ajax and will display validation errors for each given field.
50
+
51
+ On success the form will just be reseted. Please note that for each input/label there must be a wrapper like '<div class="field">...</div>'
52
+ like in the example above in order to work!
53
+
54
+
55
+ There are following options:
56
+
57
+ 'html': use your own styling instead of the provided defaults:
58
+ ---------------------------------------------------------------
59
+
60
+ html: { wrapperTag: default is 'div',
61
+ errorClass: class applied to the wrapper, default is 'error-field',
62
+ helpBlockClass: provides error-message/s styling, default is "help-block"
63
+ }
64
+ or if you're using bootstrap v3, it's just
65
+
66
+ html: "bootstrap3"
67
+
68
+ 'success': callback after (ajax)-success, accepts a function with jqXHR as first, the form-object as second and the event as third argument:
69
+ ---------------------------------------------------------------------------------------------------------------------------------------------
70
+
71
+ success: function(xhr, form, event) {
72
+
73
+ }
74
+
75
+ 'error': callback after(ajax)-error, accepts a function with jqXHR as first, the errorThrown(string) as second, the form-object as third and the event as forth argument:
76
+ --------------------------------------------------------------------------------------------------------------------------------------------------------------------------
77
+
78
+ error: function( xhr, error, form, event) {
79
+
80
+ }
81
+
82
+ 'send': callback when the form will be submitted, accepts a function with the event as only argument:
83
+ -----------------------------------------------------------------------------------------------------
84
+
85
+ send: function(event) {
86
+
87
+ }
88
+
89
+
90
+
91
+ */
92
+
93
+
94
+
95
+ var FormHandler = function(options) {
96
+ var options = options || {};
97
+ this.global_defaults = {
98
+ html: {}
99
+ }
100
+ $.extend(true, this.global_defaults, options);
101
+ this.form_objects = this.auto_detect();
102
+ }
103
+
104
+
105
+ FormHandler.prototype.filter_form_name = function(form_id) {
106
+ var form_name,form_name_parts = form_id.replace(/(new_|edit_)/g, '').split('_');
107
+ var last_part = form_name_parts[form_name_parts.length -1]
108
+ if(isNaN(parseInt(last_part))){
109
+ form_name = form_name_parts.join("_")
110
+ } else {
111
+ form_name = form_name_parts.slice(0, form_name_parts.length -1).join("_");
112
+ }
113
+ return form_name
114
+ }
115
+
116
+ FormHandler.prototype.config_form = function(form,options) {
117
+ var options = options || {};
118
+ this.form_objects[form] = $.extend(true,this.form_objects[form], options);
119
+ };
120
+
121
+ FormHandler.config_form_element = function(form, options) {
122
+ var form_name = this.filter_form_name($(form).attr('id'));
123
+ return this.config_form(form_name, options);
124
+ }
125
+
126
+ FormHandler.prototype.auto_detect = function() {
127
+ var form_objects = {};
128
+ var form_handler = this;
129
+ var global_defaults = this.global_defaults;
130
+ var count = 0;
131
+ $.each($('form'),function(index,form) {
132
+
133
+ var form_name = form_handler.filter_form_name(form.id);
134
+ var form_object = { id: form.id, ignore: false};
135
+ $.extend(true,form_object,global_defaults);
136
+ form_objects[form_name] = form_object;
137
+
138
+ })
139
+ return form_objects;
140
+ };
141
+
142
+
143
+ FormHandler.prototype.init = function() {
144
+ var instances = {};
145
+ $.each(this.form_objects, function(name, settings) {
146
+
147
+ if(!settings.ignore) {
148
+ instances[name] = new FormObject(settings.id, settings);
149
+ instances[name].set_listener()
150
+ }
151
+ })
152
+ this.instances = instances;
153
+
154
+ };
155
+
156
+
157
+
158
+ FormHandler.prototype.apply_validation_to = function(form_object_name,settings) {
159
+ var settings = settings || {};
160
+ this.instances[form_object_name].set_redirections(settings);
161
+ };
162
+
163
+ var ValidationRenderer = function(form_object,html_settings) {
164
+
165
+ this.form_object = form_object;
166
+ this.html_defaults = {
167
+ wrapperTag: 'div',
168
+ errorClass: "fh-error-field",
169
+ helpBlockClass: 'help-block'
170
+ }
171
+
172
+ this.bootstrap3_defaults = {
173
+ wrapperTag: 'div',
174
+ errorClass: "has-error",
175
+ helpBlockClass: "help-block"
176
+ }
177
+
178
+ if(typeof html_settings === "string" && html_settings === "bootstrap3") {
179
+
180
+ this.html_settings = this.bootstrap3_defaults;
181
+ } else if ( typeof html_settings === 'object') {
182
+ this.html_settings = $.extend(this.html_defaults, html_settings)
183
+ } else {
184
+ this.html_settings = this.html_defaults;
185
+ }
186
+
187
+ }
188
+
189
+ ValidationRenderer.prototype.message_tag = function(content) {
190
+ var open = "<span class='" + this.html_settings.helpBlockClass + "' >";
191
+ var close = "</span>\n";
192
+ return(open + content + close);
193
+
194
+ };
195
+
196
+ ValidationRenderer.prototype.render_messages = function(messages) {
197
+ var error_messages = "";
198
+ var that = this;
199
+
200
+ $.each(messages, function(index, message) {
201
+ error_messages += that.message_tag(message);
202
+
203
+ })
204
+ return error_messages;
205
+ };
206
+
207
+ ValidationRenderer.prototype.add_error = function(field, errors) {
208
+ var wrapper = field.closest(this.html_settings.wrapperTag);
209
+ wrapper
210
+ .toggleClass(this.html_settings.errorClass,true)
211
+ .append(this.render_messages(errors));
212
+ };
213
+
214
+ ValidationRenderer.prototype.remove_error = function(field) {
215
+ var wrapper = field.closest(this.html_settings.wrapperTag);
216
+ wrapper
217
+ .toggleClass(this.html_settings.errorClass,false)
218
+ .find("." + this.html_settings.helpBlockClass).remove();
219
+ };
220
+
221
+ ValidationRenderer.prototype.render = function(fields, errors) {
222
+ var prefix = this.form_object + "_";
223
+ var validation_renderer = this;
224
+ $.each( fields, function(key,field) {
225
+ var field_id = $("#" + key).attr('id');
226
+ var field_name = field_id.replace(prefix, '');
227
+ validation_renderer.remove_error($("#" + field));
228
+ if(errors[field_name]) {
229
+ validation_renderer.add_error($("#" + field), errors[field_name])
230
+ }
231
+ })
232
+ };
233
+
234
+
235
+ var FormObject = function(form_id, options) {
236
+
237
+ this.callbacks = {};
238
+ this.callbacks.on_success = options.success || function() {};
239
+ this.callbacks.before_submit = options.send || function() {};
240
+ this.callbacks.on_error = options.error || function() {};
241
+ this.form_id = form_id;
242
+ this.form = $("#" + form_id);
243
+ this.form_object_name = "";
244
+ this.method = "POST";
245
+ this.set_form_type();
246
+ this.html_options = options.html;
247
+ this.redirections = {};
248
+ this.set_redirections();
249
+ this.validation_renderer = new ValidationRenderer(this.form_object_name,this.html_options);
250
+
251
+
252
+ }
253
+ FormObject.prototype.set_form_type = function() {
254
+ var form = $("#" + this.form_id);
255
+ var to_array = this.form_id.split("_");
256
+
257
+ if(to_array[0] === "edit" && !isNaN( parseInt(to_array[to_array.length -1]) ) ) {
258
+
259
+ method = "PATCH"
260
+ this.form_object_name = to_array.slice(1,(to_array.length -1) ).join("_")
261
+
262
+
263
+ } else if(to_array[0] === "new") {
264
+
265
+ if(to_array.length > 2) {
266
+ this.form_object_name = to_array.slice(1,(to_array.length) ).join("_")
267
+ } else {
268
+ this.form_object_name = to_array[1]
269
+ }
270
+
271
+ }
272
+ };
273
+
274
+
275
+
276
+ FormObject.prototype.get_ajax_settings = function(event,values) {
277
+ var form_object = this;
278
+ var values = values;
279
+ var event = event;
280
+ var ajax_settings = {
281
+ method: form_object.method,
282
+ url: this.form.attr('action'),
283
+ dataType: "JSON",
284
+ data: values,
285
+ error: function(xhr, status, error) {
286
+ form_object.callbacks.on_error(xhr, error,form_object.form,event);
287
+ form_object.error(xhr.responseJSON)
288
+ },
289
+ success: function(object, status,xhr) {
290
+ form_object.callbacks.on_success(xhr,form_object.form,event)
291
+ form_object.success(xhr.responseJSON)
292
+ }
293
+ }
294
+
295
+ return ajax_settings;
296
+ };
297
+
298
+
299
+
300
+ FormObject.prototype.set_listener = function() {
301
+ var form_object = this;
302
+ this.form.on('submit', function(event) {
303
+ event.preventDefault();
304
+ event.stopPropagation();
305
+ var ajax_settings = form_object.get_ajax_settings( event, $(this).serialize() );
306
+ form_object.callbacks.before_submit(event);
307
+ $.ajax(ajax_settings)
308
+ })
309
+ };
310
+
311
+ FormObject.prototype.set_redirections = function(redirections) {
312
+ var redirections = redirections || {};
313
+ var detected = {};
314
+ this.form.find('input, select, textarea').each(function(index, field) {
315
+ if($(field).attr('data-validation')) {
316
+ var field_id = $(field).attr('id');
317
+ detected[field_id] = $(field).attr('data-validation');
318
+ if( !$(detected[field_id]).val() ) {
319
+ var original_value = $(field).val();
320
+ $("#" + detected[field_id]).val(original_value);
321
+ }
322
+ }
323
+ });
324
+ this.redirections = $.extend(detected,redirections);
325
+ };
326
+
327
+ FormObject.prototype.get_redirections = function() {
328
+ return this.redirections;
329
+ }
330
+
331
+ FormObject.prototype.get_html_options = function() {
332
+ return this.html_options;
333
+ };
334
+
335
+ FormObject.prototype.set_html_options = function(html_options) {
336
+ this.html_options = html_options;
337
+
338
+ };
339
+
340
+ FormObject.prototype.fields = function() {
341
+ var redirections = this.get_redirections();
342
+ var fields = {};
343
+ var blacklist = {};
344
+ this.form.find('input, select, textarea').each(function(index, field) {
345
+
346
+ var field_id = $(field).attr('id');
347
+
348
+
349
+ if(field_id != undefined) {
350
+ if(redirections[field_id]) {
351
+ fields[field_id] = redirections[field_id];
352
+ blacklist[redirections[field_id]] = true;
353
+ } else {
354
+ blacklist[field_id] ? null : fields[field_id] = field_id;
355
+ }
356
+ }
357
+ })
358
+ return fields;
359
+ };
360
+
361
+ FormObject.prototype.error = function(response_object) {
362
+ var errors;
363
+ response_object[this.form_object] === undefined ? errors = response_object : errors = response_object[this.form_object]
364
+ this.validation_renderer.render(this.fields(),errors);
365
+
366
+ };
367
+
368
+ FormObject.prototype.success = function() {
369
+ var form_object = this;
370
+ var fields = this.fields();
371
+ console.log(fields);
372
+ $.each(fields,function(key,value) {
373
+ var field = $("#" + value);
374
+ form_object.validation_renderer.remove_error(field);
375
+ })
376
+ this.form[0].reset();
377
+ };
378
+
379
+
380
+ FormObject.prototype.set_callbacks = function(callback, func) {
381
+ this.callbacks[callback] = func();
382
+ };
383
+
384
+ FormObject.prototype.set_html_options = function(html_options) {
385
+ this.html_options = $.extend(this.html_options, html_options);
386
+ };
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+
400
+
401
+
402
+
403
+
404
+
405
+
406
+
407
+
408
+
409
+
@@ -0,0 +1,27 @@
1
+
2
+ /*
3
+ RailsAjaxFormhandler by Davide Brancaccio
4
+
5
+ Default style-definition for error-validation
6
+
7
+ */
8
+
9
+ .fh-error-field>input[type=text],
10
+ .fh-error-field>input[type=number],
11
+ .fh-error-field>input[type=phone],
12
+ .fh-error-field>input[type=email],
13
+ .fh-error-field>select,
14
+ .fh-error-field>textarea {
15
+ border: 1px solid #bc1339;
16
+ color: 1px solid #bc1339;
17
+ }
18
+
19
+ .fh-error-field>label {
20
+ color: #bc1339;
21
+ font-weight: bolder;
22
+ }
23
+
24
+ .fh-error-field>.help-block {
25
+ color: #bc1339;
26
+ padding: 10px;
27
+ }
metadata ADDED
@@ -0,0 +1,119 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rails_ajax_formhandler
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Davide Brancaccio
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-08-28 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.14'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.14'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: sprockets-rails
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: 2.1.3
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: 2.1.3
55
+ - !ruby/object:Gem::Dependency
56
+ name: jquery-rails
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 3.1.0
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: 3.1.0
69
+ description: 'RailsAjaxFormhandler is a lightweight Javascript-plugin wich submits
70
+ your form automatically and displays server responded validation-errors by adding
71
+ styles and error-messages to the invalid input fields. '
72
+ email:
73
+ - info@yield-in.de
74
+ executables: []
75
+ extensions: []
76
+ extra_rdoc_files: []
77
+ files:
78
+ - ","
79
+ - ".gitignore"
80
+ - CODE_OF_CONDUCT.md
81
+ - Gemfile
82
+ - LICENSE.txt
83
+ - README.md
84
+ - Rakefile
85
+ - bin/console
86
+ - bin/setup
87
+ - input_validation_example1.png
88
+ - input_validation_example2.png
89
+ - lib/.DS_Store
90
+ - lib/rails_ajax_formhandler.rb
91
+ - lib/rails_ajax_formhandler/version.rb
92
+ - rails_ajax_formhandler.gemspec
93
+ - vendor/assets/javascripts/ajax_formhandler.js
94
+ - vendor/assets/stylesheets/ajax_formhandler.scss
95
+ homepage: https://github.com/brancadavide/rails_ajax_formhandler
96
+ licenses:
97
+ - MIT
98
+ metadata: {}
99
+ post_install_message:
100
+ rdoc_options: []
101
+ require_paths:
102
+ - lib
103
+ required_ruby_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ required_rubygems_version: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ requirements: []
114
+ rubyforge_project:
115
+ rubygems_version: 2.6.10
116
+ signing_key:
117
+ specification_version: 4
118
+ summary: Handling form submissions via ajax and rendering validation-errors automatically
119
+ test_files: []