Git Product home page Git Product logo

iron-form's Introduction

Published on NPM Build status Published on webcomponents.org

<iron-form>

<iron-form> is a wrapper around the HTML <form> element, that can validate and submit both custom and native HTML elements.

It has two modes: if allow-redirect is true, then after the form submission you will be redirected to the server response. Otherwise, if it is false, it will use an iron-ajax element to submit the form contents to the server.

See: Documentation, Demo.

Usage

Installation

npm install --save @polymer/iron-form

In an html file

<html>
  <head>
    <script type="module">
      import '@polymer/iron-form/iron-form.js';
      import '@polymer/paper-checkbox/paper-checkbox.js';
    </script>
  </head>
  <body>
    <iron-form>
      <form method="get" action="/form/handler">
        <input type="text" name="name" value="Batman">
        <input type="checkbox" name="donuts" checked> I like donuts<br>
        <paper-checkbox name="cheese" value="yes" checked></paper-checkbox>
      </form>
    </iron-form>
  </body>
</html>

By default, a native <button> element (or input type="submit") will submit this form. However, if you want to submit it from a custom element's click handler, you need to explicitly call the iron-form's submit method:

  <paper-button raised onclick="submitForm()">Submit</paper-button>

  function submitForm() {
    document.getElementById('iron-form').submit();
  }

In a Polymer 3 element

import {PolymerElement, html} from '@polymer/polymer';
import '@polymer/iron-form/iron-form.js';
import '@polymer/paper-checkbox/paper-checkbox.js';

class SampleElement extends PolymerElement {
  static get template() {
    return html`
    <iron-form>
      <form method="get" action="/form/handler">
        <input type="text" name="name" value="Batman">
        <input type="checkbox" name="donuts" checked> I like donuts<br>
        <paper-checkbox name="cheese" value="yes" checked></paper-checkbox>
      </form>
    </iron-form>
    `;
  }
}
customElements.define('sample-element', SampleElement);

Contributing

If you want to send a PR to this element, here are the instructions for running the tests and demo locally:

Installation

git clone https://github.com/PolymerElements/iron-form
cd iron-form
npm install
npm install -g polymer-cli

Running the demo locally

polymer serve --npm
open http://127.0.0.1:<port>/demo/

Running the tests

polymer test --npm

iron-form's People

Contributors

200puls avatar andrewebdev avatar aomarks avatar bicknellr avatar dependabot[bot] avatar dfreedm avatar e111077 avatar fejesjoco avatar hubjac1 avatar jab avatar jklein24 avatar johnthad avatar keanulee avatar mkazlauskas avatar notwaldorf avatar patgmiller avatar peterlauri avatar rickymarcon avatar rictic avatar slavko-ptitsyn avatar taylorstine avatar tedium-bot avatar thomasorlita avatar timvdlippe avatar tjmonsi avatar tjsavage avatar tmpduarte avatar tomk avatar tony19 avatar valdrinkoshi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

iron-form's Issues

String serialization for Iron-Form

Using the "iron-form" element, i get that i only can send multiple "input" with the same name using the comma separator, but i was trying to send by a separate form data.

so i have inserted a script in the "iron-form.html" file that should let me do it:

properties: {
//more attributes
      string:{
            type: Boolean,
            value: false
      }
}

into "send" method

var json;
if (this.string){
     json = this.serialize_string();
}else{
     json = this.serialize();  
}

and i added a new method

serialize_string: function() {
  var json = "";

  function addSerializedElement(el) {
    if (json != "") {
      json += "&";
    } 
    json += el.name + "=" + el.value;
  }
  for (var el, i = 0; el = this._customElements[i], i < this._customElements.length; i++) {
    if (this._useValue(el)) {
      addSerializedElement(el);
    }
  }
  for (var el, i = 0; el = this.elements[i], i < this.elements.length; i++) {
    if (!this._useValue(el) ||
        (el.hasAttribute('is') && json[el.name])) {
      continue;
    }
    addSerializedElement(el);
  }

  return json;
}

iron-form submit issue with validation

Polymer : 1.1.0
iron-form : 1.0.8

I am using paper input inside iron-form with a regex validation. The expression used is ^\d+\.?\d*$ which ensure that only the digits and a decimal point are allowed.
When i try to submit the form , it gives 400-BadRequest. however , if i keep the field blank or do not provide the decimal point then every thing works fine.
The other regex which i tried are
[0-9.]
^\d+(.\d+)?$
[0-9.]*
^\d+.?\d*$

Can someone please help me, i am really stuck with this for past couple of days

adding the link for the SO : http://stackoverflow.com/questions/32248611/polymer-iron-form-submit-issue-with-paper-input-validation

support automated invalid state management

Frameworks like Angular provide a compelling example (working plnkr):

<form name="myform">
  <input type="text" ng-model="userid" name="userid" placeholder="userid" required>
  <input type="email" ng-model="email" name="email" placeholder="email" required>
  <input type="tel" ng-model="tel" name="tel" placeholder="tel" required>
  (...)
  <input type="submit" ng-disabled="myform.$invalid" value="submit">
</form>

This example live binds the submit button's disabled state to the form's invalid state with simply ng-disabled="myform.$invalid", no matter how many inputs are added to the form. The framework manages the auto-created myform.$invalid variable, keeping it up-to-date for you with the ored together result of input.$invalid for each input in the form. So you can add n more inputs to the form and this will still work, without having to manually add references to the additional inputs in any other places.

Discussion in #60 indicated Polymer may add support for this in the future, so tracking progress here.

demonstrate binding form invalid state to submit button disabled state

A common UI pattern is to auto-validate form inputs as the user is filling out the form, and to disable the submit button until the whole form is valid, for a more responsive experience.

Both of the examples in the demo currently show off validating the form when the submit button is clicked. They demonstrate slightly different inputs as well as GET vs POST, but the second example doesn't demonstrate anything you couldn't figure out from the first.

It would be much more illustrative if one of the examples showed off <paper-input>s with auto-validate, and had its submit button's disabled state change to reflect the form's validity responsively. As a newcomer to Polymer, the intended (and cleanest) way to wire this behavior together is not clear.

Would you consider adapting the demo to show off this use case?

Thanks for your consideration and for the great work on Polymer.

Mobile A11y Testing 11/1

On Android with Talkback:

  1. in the part of the UI with the radio buttons, there seems to be one extra linear swipe needed to get from checkbox > red > next checkbox. Instead it is one swipe to get to the checkbox, one to get to the color name (e.g. red), then one swipe with nothing, then another swipe to get to the next checkbox on the line below. Not a huge deal, just odd.

  2. The Browsers drop down list doesn't notify me that it's also a text entry field. As I start typing in this field, e.g. IN, then internet explorer shows up as a suggested item. However, I have no way to swipe to this easily unless I use touch exploration. We need to think through a better way to not only notify the user that an autosuggestion is showing, but then give him/her easy access to it. "

this._requestBot

Maybe export the xhr so you can set headers?

Example, I need to be able to xhr.setRequestHeader("Authorization", ...)

serialize() does not pick all paper elements

iron-form serialize method does not pick all paper elements like paper-radio-group ,paper-dropdown-menu. These elements don't have a name attribute but the core elements do have.

Additional headers to the ajax request

Certain backend frameworks, like Django, may have additional csrf protection included. For ajax post requests django expects a X-CSRFToken header. If this token is not passed the request will raise a 403.

In cases like this it would be nice if we could set additional headers for the ajax request, similar to how we can do this on the iron-ajax element.

Feature request: non type-extension <iron-form> element

To get around the problem of redirecting to the action url, we can create a custom <iron-form> element that would

  • have a child native form to track the native inputs (like now)

  • still listen to IronFormElementBehaviour children to track custom elements (like now)

  • on submit, either

    a) use the current strategy and iron-ajax its way out or
    b) make hidden inputs that mirror all the name/values of the custom elements, add them to the child for form, and do form.submit() and let the child form take care of it

The best behaviour is that you don't need b), then you should use <form is="iron-form">, otherwise use this new, custom, element.

โœจ

Malformed form submission

When i use this element for my app. Submit form to server, the server get the form like this:

[object Object]

, it is a string. is it a bug?

facilitate common ajax form submit behaviors

For ajax forms โ€” which don't cause full page reloads when submitted (and therefore don't benefit from the browser's visual feedback that something is happening, but rather just stay in place) โ€” a common UI pattern is to disable the submit button (to prevent double submits) if there is one, and to give additional visual feedback that something is happening (e.g. show a spinner, change the submit button's label from "submit" to "loading...", etc.).

A PR I worked up for #68 indicated that this currently involves writing boilerplate like:

    function toggleLoading(event) {
      var button = document.getElementById('submitButton');
      var spinner = document.getElementById('spinner');
      button.toggleAttribute('disabled', this.request.loading);
      spinner.toggleAttribute('active', this.request.loading);
      spinner.toggleAttribute('hidden', !this.request.loading);
    }

Is there a generic way iron-form could facilitate this to reduce the need for boilerplate? For example, could iron-form accept options that would let it automatically toggle the appropriate attributes on the elements you indicate while the request is loading?

CORS error is treated as a correct response

At iron-request:succedeed (line 149), tells that status 0 is treated as a "succeed" because is the status received in a file:// protocol.
The problem is that when there is a CORS problem, the browser (at least Chrome), uses the same state. And it seems that there is no other way to differentiate between them.
I think that is more important (and secure) to understand 0 state as an unexpected result, so, an error, than as an success.
In my case, the user thought he saved an entity, and continued working.

Unable to access JSON response

Hi,

I am unable to access the JSON data from my api as part of 'iron-form-response'. I am sending login data to an api on a local development server (running Django w/ django-rest-framework to handle the api). Chrome DevTools show the following response, which is the correct JSON data that I want to work with (I plan to store the access token as a cookie).

{"token":"967b6b0295a9f50cf9b37f554e0f11690e79f478"}

The headers are as follows (the request URL is my local IP, with the Django development server on port 80):

General
Request URL:http://192.168.0.13/api-token-auth/
Request Method:POST
Status Code:200 OK
Remote Address:192.168.0.13:80

Response Headers
Access-Control-Allow-Origin:*
Allow:POST, OPTIONS
Content-Type:application/json
Date:Sun, 06 Dec 2015 20:09:33 GMT
Server:WSGIServer/0.2 CPython/3.4.3
Vary:Cookie

Request Headers
accept:application/json
Accept-Encoding:gzip, deflate
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:48
content-type:application/x-www-form-urlencoded
DNT:1
Host:192.168.0.13
Origin:http://localhost:5000
Pragma:no-cache
Referer:http://localhost:5000/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36

Form Data
view URL encoded
username:[my username]
password:[my password]

As you can see, the content-type is set as 'application/json', and the response seems to be perfectly formatted JSON.

My javascript is running the following code:

var form = document.getElementById('loginForm');
form.addEventListener('iron-form-submit', function(event) {
  document.getElementById('loginSpinner').setAttribute('active', '');
  console.log(event);
});
form.addEventListener('iron-form-response', function(event) {
  document.getElementById('loginSpinner').removeAttribute('active');
  console.log(event);
});
form.addEventListener('iron-form-error', function(event) {
  document.getElementById('loginSpinner').removeAttribute('active');
  console.log(event);
});

The console.log statements should be printing out the request and response information in the event's 'detail' property. While this works for the request...

Event {isTrusted: false, detail: Object}
  bubbles: true
  cancelBubble: false
  cancelable: false
  currentTarget: null
  defaultPrevented: false
  detail: Object
    password: "pass"
    username: "[email protected]"
    __proto__: Object
  eventPhase: 0
  isTrusted: false
  isTrusted: false
  path: Array[6]
  returnValue: true
  srcElement: form#loginForm
  target: form#loginForm
  timeStamp: 1449432572701
  type: "iron-form-submit"
  __proto__: Event

... it does not work as well for the response:

Event {isTrusted: false, detail: iron-request}
  bubbles: true
  cancelBubble: false
  cancelable: false
  currentTarget: null
  defaultPrevented: false
  detail: iron-request
    __data__: Object
    __domApi: DomApi
    _aboveConfig: Object
    _clients: null
    _clientsReadied: true
    _config: Object
    _debouncers: Object
    _handlers: Array[0]
    _ownerShadyRoot: null
    _readied: true
    aborted: false
    accessKey: ""
    attributes: NamedNodeMap
    baseURI: null
    childElementCount: 0
    childNodes: NodeList[0]
    children: HTMLCollection[0]
    classList: DOMTokenList[0]
    className: ""
    clientHeight: 0
    clientLeft: 0
    clientTop: 0
    clientWidth: 0
    completes: Promise
    contentEditable: "inherit"
    customStyle: Object
    dataHost: undefined
    dataset: DOMStringMap
    dir: ""
    domHost: null
    draggable: false
    errored: false
    firstChild: null
    firstElementChild: null
    hidden: true
    id: ""
    innerHTML: ""
    innerText: ""
    isContentEditable: false
    lang: ""
    lastChild: null
    lastElementChild: null
    localName: "iron-request"
    namespaceURI: "http://www.w3.org/1999/xhtml"
    nextElementSibling: null
    nextSibling: null
    nodeName: "IRON-REQUEST"
    nodeType: 1
    nodeValue: null
    offsetHeight: 0
    offsetLeft: 0
    offsetParent: null
    offsetTop: 0
    offsetWidth: 0
    onabort: null
    onautocomplete: null
    onautocompleteerror: null
    onbeforecopy: null
    onbeforecut: null
    onbeforepaste: null
    onblur: null
    oncancel: null
    oncanplay: null
    oncanplaythrough: null
    onchange: null
    onclick: null
    onclose: null
    oncontextmenu: null
    oncopy: null
    oncuechange: null
    oncut: null
    ondblclick: null
    ondrag: null
    ondragend: null
    ondragenter: null
    ondragleave: null
    ondragover: null
    ondragstart: null
    ondrop: null
    ondurationchange: null
    onemptied: null
    onended: null
    onerror: null
    onfocus: null
    oninput: null
    oninvalid: null
    onkeydown: null
    onkeypress: null
    onkeyup: null
    onload: null
    onloadeddata: null
    onloadedmetadata: null
    onloadstart: null
    onmousedown: null
    onmouseenter: null
    onmouseleave: null
    onmousemove: null
    onmouseout: null
    onmouseover: null
    onmouseup: null
    onmousewheel: null
    onpaste: null
    onpause: null
    onplay: null
    onplaying: null
    onprogress: null
    onratechange: null
    onreset: null
    onresize: null
    onscroll: null
    onsearch: null
    onseeked: null
    onseeking: null
    onselect: null
    onselectstart: null
    onshow: null
    onstalled: null
    onsubmit: null
    onsuspend: null
    ontimeupdate: null
    ontoggle: null
    onvolumechange: null
    onwaiting: null
    onwebkitfullscreenchange: null
    onwebkitfullscreenerror: null
    onwheel: null
    outerHTML: "<iron-request hidden=""></iron-request>"
    outerText: ""
    ownerDocument: document
    parentElement: null
    parentNode: null
    prefix: null
    previousElementSibling: null
    previousSibling: null
    progress: Object
    rejectCompletes: ()
    resolveCompletes: ()
    response: Object
    root: iron-request
    scrollHeight: 0
    scrollLeft: 0
    scrollTop: 0
    scrollWidth: 0
    shadowRoot: null
    spellcheck: true
    status: 200
    statusText: "OK"
    style: CSSStyleDeclaration
    succeeded: true
    tabIndex: -1
    tagName: "IRON-REQUEST"
    textContent: ""
    timedOut: false
    title: ""
    translate: true
    url: "http://192.168.0.13/api-token-auth/"
    webkitdropzone: ""
    xhr: XMLHttpRequest
    __proto__: iron-request
  eventPhase: 0
  isTrusted: false
  isTrusted: false
  path: Array[6]
  returnValue: true
  srcElement: form#loginForm
  target: form#loginForm
  timeStamp: 1449432573472
  type: "iron-form-response"
  __proto__: Event

I am not sure why there is an iron-request object instead of formatted JSON, or how I can go about accessing the response. Any help with this would be greatly appreciated.

--Matt

validate() doesn't validate extended native element

<input is="iron-input"...> isn't registered as a custom elements and validate() assumes it has already been validated :

Custom elements that extend a native element will also appear in this list, but they've already been validated.

Sample code:

    <profile-name-validator></profile-name-validator>
    <form is="iron-form" id="form" method="post" action="/form/handler"
      <input is="iron-input" name="name" required validator="profile-name-validator"></input>
  </form>

input's validate() works but it is never called by iron-form's validate()

$0 [input]
$0.validate()
false
$0.parentElement.validate()
true

I guess the solution for now is to write a custom element to wrap iron-input or just use a paper-input which works fine (but is a pain to restyle).

API docs should clarify handling of form data

Currently, we hand contentType off to iron-ajax, which slips it under the hood to iron-request, which may or may not do magic stuff to the form data.

To make this super clear, we should mention how contentType is used.

Even though a) method is a native property of the form element, and b) we show it in the head docs, I think it would be nice to include it in the API reference if possible. Or if not, at least mention that it's a standard part of the <form> API so people don't go digging through the API doc scratching their heads.

Related: PolymerElements/iron-ajax#139

Can't get response when use iron-form

I don't know how the bug happened.But I check the code in iron-ajax.
image
image

OK. My bad. A mistake is caused because my server response a wrong JSON format.

Update validate() docs to state that only named form elements will be validated, or change validation behaviour to include un-named elements.

#20 introduced a breaking change in validation behaviour such that only named elements are validated. The break occurred for anyone that was relying on validation for un-named form elements.

At that time, one reason given was an inability to serialise un-named form elements. Given that #22 decoupled validation from form submission/serialisation, should we still have the constraint that only named form elements will be validated? Validation isn't dependent on the name attribute, so it seems an unnecessary constraint for the validation phase.

If this constraint is to be retained, can the validate() documentation be updated to explicitly call this out?

Thanks!

POST not sending body

By creating a POST form the method is send to the iron form in Lower Case, but it is being matched with a Upper Case 'POST'.

This causes the element not to add the requestBody and only request params.

  console.log(this.method);          // shows 'post'
  if (this.method == 'POST') {
      console.log('passed');         // not passed
      this._requestBot.body = JSON.stringify(json);
  }

_validate() should be a public API

I have situations where I want to validate the form without calling submit(). I'm guessing others also have this requirement, and like me are calling _validate() to achieve this, so this shouldn't technically be a breaking change, but it probably will be.

What if custom _getValidity method needs to make an Ajax request?

https://github.com/PolymerElements/iron-form/blob/master/demo/simple-element.html demonstrates an element with a custom _getValidity method.

Let's say you have a <paper-input type="email" required auto-validate> in your iron-form. But it needs customized _getValidity logic because once the client-side has determined it's a valid email address, it has to ask the server if the email address is already in use. This requires an Ajax request. But _getValidity isn't allowed to return a promise, it must return true/false. Are you meant to block on the Ajax request (bad practice?), or should the _getValidity API accommodate this some other way?

Thanks for any tips and for the great work on Polymer.

Hooking into form pre-submission

Is it possible to hook into the form flow prior to submission? The use-case would be to modify the json to move the attributes inside an object.

Now:

{"foo": "bar"}

Desired:

{
  "list": {
    "foo": "bar"
  }
}

Support for paper elements

Please provide support for paper-radio-group, paper-radio-button and paper-checkbox.
Currently they are ignored in the request data.

`validate()` does not validate non-named elements

I think that validate() should validate type or required of <input>.

why is this valid?

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="bower_components/iron-form/iron-form.html">
  <link rel="import" href="bower_components/iron-input/iron-input.html">

  <script>
    function clickHandler(event) {
      var form = Polymer.dom(event).localTarget.parentElement;
      if (form.validate()) {
        console.log("OK!");
      } else {
        console.log("Invalid!");
      }
    }
  </script>
</head>
<body>
  <form is="iron-form" method="get" action="/">
    <label>iron-input[type=email][required]</label><br/>
    <input is="iron-input" type="email" required/><br/>
    <button onclick="clickHandler(event)">Submit</button>
  </form>
</body>
</html>

image

image

Thanks.

Event documentation is opaque regarding what is in event.detail

I am finding almost impossible, without trawling through the code to figure out what is in event.detail when the iron-form-response is received.

I had naively thought it would contain the response, but I think (from poking around in developer tools in chrome) that it actually contains the iron-request. I think I can get at the response one level down from that.

firebase?

I would like to use this with firebase, but it's tied directly with iron-ajax, I am not using the rest api with firebase. It would be nice to have more control over the form action...

Duplicate reading of custom elements' value

  • Currently, iron-form tries to evade duplicate reading from same form elements using hasAttribute('is'). However, not every native form elements in custom element has "is" attribute. Therefore every routine that uses hasAttribute("is") as flag can be malfunctioning.

  • Examples

    • <input is="iron-input"> : has "is" attribute. Fine.
    • <textarea> in iron-autogrow-textarea : does not have "is" attribute. Therefore the value of <paper-textarea will be referenced twice. (if it has "name" attribute), and return the array with duplicated values. Please read the code below.

    iron-form 166-181

         // 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 (!el.name || !this._useValue(el) ||
               (el.hasAttribute('is') && json[el.name])) {
             continue;
           }
           addSerializedElement(el);
         }

textarea in <paper-textarea> (part of paper-input) will return false when el.hasAttribute('is') is called. If <paper-textarea> has name and its type is not radio or checkbox, If statement will be false and addSerializedElement will call again even it is already called before.

  • Currently affected methods
    • serialize
    • validate
    • Now paper-textarea is not working. However, if someone try to use <paper-toggle-button> as a part of iron-form, it will not work too.

events does not provide access to the response object

Events iron-form-error and iron-form-response don't provide access to the event.detail.response object.
While iron-form-error doesn't have it at all (it allows access only to the request), in iron-form-response event.detail.response is set to null.

iron-form and POST method problem

From @Krazitchek on June 24, 2015 16:35

Hello, i use Polymer starter kit 1.0.2 and i'm trying to use iron-form based on (little) documentation i found.

My method form is "post" and contain only one input.

My form "action" is a PHP script (add.php) showing content of $_GET and $_POST:

echo '<pre>';
print_r($_POST);
print_r($_GET);
echo '</pre>';

My form component (form_eclp.html) is:

<dom-module id="my-form">
    <template>
        <div class="horizontal center-center layout">
            <div>
                <div class="horizontal-section">
                    <form is="iron-form" id="formGet" method="post" action="add.php">
                        <paper-input name="name" label="Name" required></paper-input>
                        <br><br><br>
                        <paper-button raised onclick="clickHandler(event)">Submit</paper-button>
                    </form>
                </div>
            </div>
        </div>
    </template>
    <script>

        function clickHandler(event) {
            Polymer.dom(event).localTarget.parentElement.submit();
        }

        Polymer({
            is: 'my-form',
            listeners: {
                'iron-form-response': 'formResponse'
            },
            formResponse: function(e) {
                // ?????????
            }
        });
    </script>
</dom-module>

I call if from:

<link rel="import" href="form_eclp.html">
<my-form></my-form>

When i click the submit button after entering the text 'test' in name input, i can see in the network tab of the browser developper tools that it's a POST request, ok, but the url is add.php?name=test, and in the response tab i have:

<pre>Array
(
)
Array
(
    [name] => test
)
</pre>

According to my form action (add.php script), first array is for $_POST and the second $_GET.

I can see, despite form method="post", it's a "get" request because only $_GET is populated, there is nothing in $_POST.

Have i missed something ?... i don't understand.
polymer

Copied from original issue: Polymer/polymer#1955

Safari-specific duplicate reading of custom elements' value

  • This is different issue from #12 : similar behavior but different reason.
  • In safari, some custom elements are read three times.
      // 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);
      }
  • Example: paper-input
    • Intended behavior: iron-form reads paper-input and passing native elements logic
    • In Safari : in custom element reading code, iron-form reads paper-input and iron-input. In form's native code read part, iron-form also reads input field, even they are same element (with inheritance) with same name.
    • addSerializedElement(el) stacks values if same element is already read. Therefore, generated json field looks like: "name":['value','value','value']
  • Reason
    • In Safari, custom element has "is" attribute (can read as element.is) however existence of "is" attribute cannot be confirmed with hasAttribute method. hasAttribute('is') returns false.
    • element.is of native elements return false in Safari / undefined in Chrome.
    • It could be webcomponents.js problem.

Support for PUT, PATCH and DELETE

Hi,

I tried to use PUT, PATCH and DELETE with the element, but it automatically fallback to GET. After some tests, I find out that it wasn't the element that was doing that, but something else (polymer ?).

Is there any plan to implement those methods into polymer ?

Thank you

HTML Form submit event not being triggered

From @tjsavage on July 21, 2015 20:37

From @steelbrain on July 21, 2015 1:3

Consider you have the following markup

<form id="form" action="javascript:" method="post">
  <input type="text" name="username" />
</form>
<script>
var form = document.getElementById("form")
form.on('submit', function(e){
  e.preventDefault()
  console.log("Hey")
})
</script>

now if you focus the input element and press enter, the submit event won't be triggered.
Now if you add <button>Something</button> without the form bounds, pressing enter after focusing the event or clicking the button, both would work.
Now if you replace that button with a paper-button <paper-button raised>Hey</paper-button>, submit will be impossible again because there's no button in the form.
Now if you add is="iron-form" to the tag, and the form will be submitted by the paper-button now but it won't trigger the native submit event, not even the iron-form-submit event.

I am using Google Chrome 43.0.2357.134

Copied from original issue: Polymer/polymer#2128

Copied from original issue: PolymerElements/paper-button#34

Incompatibility with "form" dom element

i recently found a bug when i am trying to send a "input" with name "action".

that happen because in the native "form" element all "input" name is set as a property in the javascript dom so the original value of "action" attribute is replaced by the "input" value with name "action".

for fix that bug, i add a "get" method in the "iron-form.html" file for get the real value for the "form" element like this:

/**
 * Get the real action 
 */ 
get real_action(){
  return this.getAttribute('action');
}

and so, i replaced in the "submit" method like this:

this._requestBot.url = this.real_action;

required sample custom element in the demo is not actually required

Reproduction steps:

  1. Go to the demo
  2. Fill in the required Name and Favourite animal fields and check the two (unchecked) required checkboxes
  3. Click SUBMIT

Expected behavior: The form does not submit because the required custom element is empty, and the required custom element gets its "invalid" styling

Actual behavior: The form submits, the required custom element does not get its "invalid" styling.

screen shot 2015-10-03 at 15 15 21

Please let me know if I'm missing something, as I've been hoping to make progress on #56 and GoogleWebComponents/google-recaptcha#11, and if this is broken in iron-form I better wait for the fix first. Thanks in advance for taking a look.

Support posting structured json data

Currently form data is serialized into a flat structure. Would be great if it serializes into structured data as below.

Current:
{
'user.name': 'abc',
'user.address.street': '123 abc',
'user.address.city': 'xyz'
}

Expected:
'user': {
'name': 'abc',
'address': {
'street': '123 abc',
'city': 'xyz'
}
}

this.submit() in FF calls native form function

When testing iron-form using Firefox, the this.submit() of the iron-form element is never getting called. Instead, it it is calling the native submit function causing a page refresh.

Confirmed this by changing the name of the submit function to see it work as expected

iron-form body data malformed

POST requests using iron-form and sending JSON as request body, is misinterpreted by requesting URL. My test shows a simple nodejs server that accepts POST requests and prints out body using body-parser API. I'm using Polymer 1.0 with iron-form inside a custom component.

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/iron-form/iron-form.html">
<link rel="import" href="../bower_components/paper-input/paper-input.html">
<link rel="import" href="../bower_components/paper-button/paper-button.html">

<dom-module id="app-bear-form">
    <style>
        #submit {
            background-color: #4CAF50;
            color: white;
            float: right;
        }
    </style>
    <template>

        <p>Create a bear</p>
        <form is="iron-form" id="form" method='POST' action="http://192.168.63.133:8080/api/bears">
            <paper-input label="Bear Name" name="name" required="true"></paper-input>
            <paper-input label="Bear Age" name="age"></paper-input>
        </form>
        <br/>
        <paper-button onclick="submitForm()" label="Create Bear" id="submit" raisedButton>Create</paper-button><br/>

    </template>
    <script>
    onclick="submitForm()"

        function submitForm() { 
            document.getElementById('form').submit();
        }

        Polymer({
            is: 'app-bear-form',
            ready: function() {

            },
            createBear: function() {
                this.$.form.submit();

            },
        });
    </script>
</dom-module>

The request body json data:
image

demonstrate reacting to form's submitted state changes

Ajax forms transition between submitted states like this:
not submitted โ†’ submitted / request in flight โ†’ (response received, so back to) not submitted

A common UI pattern is to disable the submit button and change its text from "submit" to "loading..." (show a spinner, etc.) while the request is in flight.

An iron-form is submitted via an internal iron-ajax element. iron-ajax has a "loading" property for whether a request is in flight. Does iron-form expose this property so the pattern above can be expressed simply? Or do we have to duplicate the logic that keeps track of the "loading" state on the form itself?

Would you consider demonstrating this pattern in the iron-form demo page to show off the recommended way to do this? Thanks for your consideration.

multipart/form-data support

I'm trying to set the content-type to multipart/form-data so I can upload images to a Go server, but I'm getting the following error when trying to parse the form on my server:

no multipart boundary param in Content-Type

Is multipart/form-data not supported, or am I missing something? Here's a reduced example which produces the issue:

<dom-module id="file-upload">
    <template>
        <form is="iron-form" id="form" content-type="multipart/form-data" action="http://localhost:9090/upload" method="post">  
            <input name="field-1" type="file" accept="image/*" required><br>
            <button on-tap="submit">submit</button>
        </form>
    </template>
</dom-module>
<script>
    Polymer({
        is: "file-upload",
        submit: function() {
            this.$.form.submit();
        }
    });
</script>

I should note that I can upload images using a regular form, so I know it isn't a problem with my server.

Multi select values

Hi,

When I take a look to the iron-form submitted values, it seems that for a native multi select input, it only keep one value (the top one). Is that a bug or do you know how to get around of that ?

Thanks !

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.