Blame view

bower_components/iron-form/iron-form.html 12.5 KB
73bcce88   luigser   COMPONENTS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  <!--
  @license
  Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
  This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
  The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
  The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
  Code distributed by Google as part of the polymer project is also
  subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
  -->
  
  <link rel="import" href="../polymer/polymer.html">
  <link rel="import" href="../iron-ajax/iron-ajax.html">
  
  <script>
  /*
a1a3bc73   Luigi Serra   graphs updates
16
  `<iron-form>` is an HTML `<form>` element that can validate and submit any custom
73bcce88   luigser   COMPONENTS
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  elements that implement `Polymer.IronFormElementBehavior`, as well as any
  native HTML elements.
  
  It supports both `get` and `post` methods, and uses an `iron-ajax` element to
  submit the form data to the action URL.
  
    Example:
  
      <form is="iron-form" id="form" method="post" action="/form/handler">
        <paper-input name="name" label="name"></paper-input>
        <input name="address">
        ...
      </form>
  
  By default, a native `<button>` element will submit this form. However, if you
  want to submit it from a custom element's click handler, you need to explicitly
  call the form's `submit` method.
  
    Example:
  
      <paper-button raised onclick="submitForm()">Submit</paper-button>
  
      function submitForm() {
        document.getElementById('form').submit();
      }
  
a1a3bc73   Luigi Serra   graphs updates
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  To customize the request sent to the server, you can listen to the `iron-form-presubmit`
  event, and modify the form's[`iron-ajax`](https://elements.polymer-project.org/elements/iron-ajax)
  object. However, If you want to not use `iron-ajax` at all, you can cancel the
  event and do your own custom submission:
  
    Example of modifying the request, but still using the build-in form submission:
  
      form.addEventListener('iron-form-presubmit', function() {
        this.request.method = 'put';
        this.request.params = someCustomParams;
      });
  
    Example of bypassing the build-in form submission:
  
      form.addEventListener('iron-form-presubmit', function(event) {
        event.preventDefault();
        var firebase = new Firebase(form.getAttribute('action'));
        firebase.set(form.serialize());
      });
  
73bcce88   luigser   COMPONENTS
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
  @demo demo/index.html
  */
  
    Polymer({
  
      is: 'iron-form',
  
      extends: 'form',
  
      properties: {
        /**
         * Content type to use when sending data.
         */
        contentType: {
          type: String,
          value: "application/x-www-form-urlencoded"
        },
  
        /**
         * By default, the form will display the browser's native validation
         * UI (i.e. popup bubbles and invalid styles on invalid fields). You can
         * manually disable this; however, if you do, note that you will have to
         * manually style invalid *native* HTML fields yourself, as you are
         * explicitly preventing the native form from doing so.
         */
        disableNativeValidationUi: {
          type: Boolean,
          value: false
        },
  
        /**
        * Set the withCredentials flag when sending data.
        */
        withCredentials: {
          type: Boolean,
          value: false
eb240478   Luigi Serra   public room cards...
99
100
101
102
103
104
105
106
107
108
109
110
111
        },
  
        /**
        * HTTP request headers to send
        *
        * Note: setting a `Content-Type` header here will override the value
        * specified by the `contentType` property of this element.
        */
        headers: {
          type: Object,
          value: function() {
            return {};
          }
a1a3bc73   Luigi Serra   graphs updates
112
113
114
115
116
117
118
        },
  
        /**
        * iron-ajax request object used to submit the form.
        */
        request: {
          type: Object,
73bcce88   luigser   COMPONENTS
119
120
        }
      },
a1a3bc73   Luigi Serra   graphs updates
121
  
73bcce88   luigser   COMPONENTS
122
123
124
125
126
127
128
      /**
       * Fired if the form cannot be submitted because it's invalid.
       *
       * @event iron-form-invalid
       */
  
      /**
a1a3bc73   Luigi Serra   graphs updates
129
130
131
132
133
134
       * Fired before the form is submitted.
       *
       * @event iron-form-presubmit
       */
  
      /**
73bcce88   luigser   COMPONENTS
135
136
137
138
139
       * Fired after the form is submitted.
       *
       * @event iron-form-submit
       */
  
a1a3bc73   Luigi Serra   graphs updates
140
141
142
143
144
145
       /**
        * Fired after the form is reset.
        *
        * @event iron-form-reset
        */
  
73bcce88   luigser   COMPONENTS
146
      /**
a1a3bc73   Luigi Serra   graphs updates
147
148
      * Fired after the form is submitted and a response is received. An
      * IronRequestElement is included as the event.detail object.
73bcce88   luigser   COMPONENTS
149
150
151
152
153
      *
      * @event iron-form-response
      */
  
      /**
a1a3bc73   Luigi Serra   graphs updates
154
155
       * Fired after the form is submitted and an error is received. An
       * IronRequestElement is included as the event.detail object.
73bcce88   luigser   COMPONENTS
156
157
158
159
160
161
       *
       * @event iron-form-error
       */
      listeners: {
        'iron-form-element-register': '_registerElement',
        'iron-form-element-unregister': '_unregisterElement',
a1a3bc73   Luigi Serra   graphs updates
162
163
        'submit': '_onSubmit',
        'reset': '_onReset'
73bcce88   luigser   COMPONENTS
164
165
166
167
      },
  
      ready: function() {
        // Object that handles the ajax form submission request.
a1a3bc73   Luigi Serra   graphs updates
168
169
170
        this.request = document.createElement('iron-ajax');
        this.request.addEventListener('response', this._handleFormResponse.bind(this));
        this.request.addEventListener('error', this._handleFormError.bind(this));
73bcce88   luigser   COMPONENTS
171
172
173
  
        // Holds all the custom elements registered with this form.
        this._customElements = [];
a1a3bc73   Luigi Serra   graphs updates
174
175
        // Holds the initial values of the custom elements registered with this form.
        this._customElementsInitialValues = [];
73bcce88   luigser   COMPONENTS
176
177
178
      },
  
      /**
a1a3bc73   Luigi Serra   graphs updates
179
       * Submits the form.
73bcce88   luigser   COMPONENTS
180
181
182
183
184
185
186
187
188
189
190
191
192
193
       */
      submit: function() {
        if (!this.noValidate && !this.validate()) {
          // In order to trigger the native browser invalid-form UI, we need
          // to do perform a fake form submit.
          if (!this.disableNativeValidationUi) {
            this._doFakeSubmitForValidation();
          }
          this.fire('iron-form-invalid');
          return;
        }
  
        var json = this.serialize();
  
a1a3bc73   Luigi Serra   graphs updates
194
195
196
197
198
199
200
201
202
203
204
        // Native forms can also index elements magically by their name (can't make
        // this up if I tried) so we need to get the correct attributes, not the
        // elements with those names.
        this.request.url = this.getAttribute('action');
        this.request.method = this.getAttribute('method');
        this.request.contentType = this.contentType;
        this.request.withCredentials = this.withCredentials;
        this.request.headers = this.headers;
  
        if (this.method.toUpperCase() === 'POST') {
          this.request.body = json;
73bcce88   luigser   COMPONENTS
205
        } else {
a1a3bc73   Luigi Serra   graphs updates
206
          this.request.params = json;
73bcce88   luigser   COMPONENTS
207
208
        }
  
a1a3bc73   Luigi Serra   graphs updates
209
210
211
212
213
214
        // Allow for a presubmit hook
        var event = this.fire('iron-form-presubmit', {}, {cancelable: true});
        if(!event.defaultPrevented) {
          this.request.generateRequest();
          this.fire('iron-form-submit', json);
        }
73bcce88   luigser   COMPONENTS
215
216
      },
  
a1a3bc73   Luigi Serra   graphs updates
217
218
219
220
221
      /**
       * Handler that is called when the native form fires a `submit` event
       *
       * @param {Event} event A `submit` event.
       */
73bcce88   luigser   COMPONENTS
222
223
224
225
226
227
228
229
230
231
232
233
      _onSubmit: function(event) {
        this.submit();
  
        // Don't perform a page refresh.
        if (event) {
          event.preventDefault();
        }
  
        return false;
      },
  
      /**
a1a3bc73   Luigi Serra   graphs updates
234
235
236
237
238
239
240
241
242
       * Handler that is called when the native form fires a `reset` event
       *
       * @param {Event} event A `reset` event.
       */
      _onReset: function(event) {
        this._resetCustomElements();
      },
  
      /**
73bcce88   luigser   COMPONENTS
243
244
245
246
       * Returns a json object containing name/value pairs for all the registered
       * custom components and native elements of the form. If there are elements
       * with duplicate names, then their values will get aggregated into an
       * array of values.
a1a3bc73   Luigi Serra   graphs updates
247
       *
e619a3b0   Luigi Serra   Controllet cross ...
248
       * @return {!Object}
73bcce88   luigser   COMPONENTS
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
       */
      serialize: function() {
        var json = {};
  
        function addSerializedElement(el) {
          // If the name doesn't exist, add it. Otherwise, serialize it to
          // an array,
          if (!json[el.name]) {
            json[el.name] = el.value;
          } else {
            if (!Array.isArray(json[el.name])) {
              json[el.name] = [json[el.name]];
            }
            json[el.name].push(el.value);
          }
        }
  
        // Go through all of the registered custom components.
        for (var el, i = 0; el = this._customElements[i], i < this._customElements.length; i++) {
          if (this._useValue(el)) {
            addSerializedElement(el);
          }
        }
  
        // Also go through the form's native elements.
        for (var el, i = 0; el = this.elements[i], i < this.elements.length; i++) {
          // Checkboxes and radio buttons should only use their value if they're checked.
          // Also, custom elements that extend native elements (like an
          // `<input is="fancy-input">`) will appear in both lists. Since they
          // were already added as a custom element, they don't need
          // to be re-added.
          if (!this._useValue(el) ||
              (el.hasAttribute('is') && json[el.name])) {
            continue;
          }
          addSerializedElement(el);
        }
  
        return json;
      },
  
      _handleFormResponse: function (event) {
eb240478   Luigi Serra   public room cards...
291
        this.fire('iron-form-response', event.detail);
73bcce88   luigser   COMPONENTS
292
293
294
295
296
297
298
      },
  
      _handleFormError: function (event) {
        this.fire('iron-form-error', event.detail);
      },
  
      _registerElement: function(e) {
a1a3bc73   Luigi Serra   graphs updates
299
300
301
302
303
304
305
        var element = e.target;
        element._parentForm = this;
        this._customElements.push(element);
  
        // Save the original value of this input.
        this._customElementsInitialValues.push(
            this._usesCheckedInsteadOfValue(element) ? element.checked : element.value);
73bcce88   luigser   COMPONENTS
306
307
308
309
310
311
312
313
      },
  
      _unregisterElement: function(e) {
        var target = e.detail.target;
        if (target) {
          var index = this._customElements.indexOf(target);
          if (index > -1) {
            this._customElements.splice(index, 1);
a1a3bc73   Luigi Serra   graphs updates
314
            this._customElementsInitialValues.splice(index, 1);
73bcce88   luigser   COMPONENTS
315
316
317
318
319
320
321
322
323
324
325
326
327
328
          }
        }
      },
  
      /**
       * Validates all the required elements (custom and native) in the form.
       * @return {boolean} True if all the elements are valid.
       */
      validate: function() {
        var valid = true;
  
        // Validate all the custom elements.
        var validatable;
        for (var el, i = 0; el = this._customElements[i], i < this._customElements.length; i++) {
e619a3b0   Luigi Serra   Controllet cross ...
329
          if (el.required && !el.disabled) {
73bcce88   luigser   COMPONENTS
330
            validatable = /** @type {{validate: (function() : boolean)}} */ (el);
e619a3b0   Luigi Serra   Controllet cross ...
331
332
333
            // Some elements may not have correctly defined a validate method.
            if (validatable.validate)
              valid = !!validatable.validate() && valid;
73bcce88   luigser   COMPONENTS
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
          }
        }
  
        // Validate the form's native elements.
        for (var el, i = 0; el = this.elements[i], i < this.elements.length; i++) {
          // Custom elements that extend a native element will also appear in
          // this list, but they've already been validated.
          if (!el.hasAttribute('is') && el.willValidate && el.checkValidity && el.name) {
            valid = el.checkValidity() && valid;
          }
        }
  
        return valid;
      },
  
a1a3bc73   Luigi Serra   graphs updates
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
      /**
       * Returns whether the given element is a radio-button or a checkbox.
       * @return {boolean} True if the element has a `checked` property.
       */
      _usesCheckedInsteadOfValue: function(el) {
        if (el.type == 'checkbox' ||
            el.type == 'radio' ||
            el.getAttribute('role') == 'checkbox' ||
            el.getAttribute('role') == 'radio' ||
            el._hasIronCheckedElementBehavior) {
          return true;
        }
        return false;
      },
  
73bcce88   luigser   COMPONENTS
364
365
366
367
368
369
370
371
372
      _useValue: function(el) {
        // Skip disabled elements or elements that don't have a `name` attribute.
        if (el.disabled || !el.name) {
          return false;
        }
  
        // Checkboxes and radio buttons should only use their value if they're
        // checked. Custom paper-checkbox and paper-radio-button elements
        // don't have a type, but they have the correct role set.
a1a3bc73   Luigi Serra   graphs updates
373
        if (this._usesCheckedInsteadOfValue(el))
73bcce88   luigser   COMPONENTS
374
          return el.checked;
73bcce88   luigser   COMPONENTS
375
376
377
378
379
380
381
382
383
384
385
386
        return true;
      },
  
      _doFakeSubmitForValidation: function() {
        var fakeSubmit = document.createElement('input');
        fakeSubmit.setAttribute('type', 'submit');
        fakeSubmit.style.display = 'none';
        this.appendChild(fakeSubmit);
  
        fakeSubmit.click();
  
        this.removeChild(fakeSubmit);
a1a3bc73   Luigi Serra   graphs updates
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
      },
  
      /**
       * Resets all non-disabled form custom elements to their initial values.
       */
      _resetCustomElements: function() {
        // Reset all the registered custom components. We need to do this after
        // the native reset, since programmatically changing the `value` of some
        // native elements (iron-input in particular) does not notify its
        // parent `paper-input`, which will now display the wrong value.
        this.async(function() {
          for (var el, i = 0; el = this._customElements[i], i < this._customElements.length; i++) {
            if (el.disabled)
              continue;
  
            if (this._usesCheckedInsteadOfValue(el)) {
              el.checked = this._customElementsInitialValues[i];
            } else {
              el.value = this._customElementsInitialValues[i];
            }
          }
  
          this.fire('iron-form-reset');
        }, 1);
73bcce88   luigser   COMPONENTS
411
412
413
414
415
      }
  
    });
  
  </script>