From 03bc5a407937d61e0fe6cccfc73665432276450d Mon Sep 17 00:00:00 2001 From: Stephen Demjanenko Date: Sat, 21 Feb 2015 12:33:49 -0800 Subject: [PATCH] Update form's model if the input is pristine and its value changes; test This fixes a case where a form initializes with default values loaded from the server. If an update comes in from the server and the user has not touched the field (its pristine) then update the field's value. This feature will help track if the user has actually made any changes from the default value that the form was/would have been initialized with. --- specs/Formsy-spec.js | 52 ++++++++++++++++++++++++++++++++++++++++++++ src/main.js | 9 ++++++++ 2 files changed, 61 insertions(+) diff --git a/specs/Formsy-spec.js b/specs/Formsy-spec.js index c129b59..1909e6a 100755 --- a/specs/Formsy-spec.js +++ b/specs/Formsy-spec.js @@ -120,6 +120,58 @@ describe('Formsy', function () { }); + it('should allow a dynamically updated input to update the form-model', function (done) { + + var forceUpdate = null; + var model = null; + var TestInput = React.createClass({ + mixins: [Formsy.Mixin], + changeValue: function (event) { + this.setValue(event.target.value); + }, + render: function () { + return + } + }); + + var input; + var TestForm = React.createClass({ + componentWillMount: function () { + forceUpdate = this.forceUpdate.bind(this); + }, + onSubmit: function (formModel) { + model = formModel; + }, + render: function () { + input = ; + + return ( + + {input} + ); + } + }); + var form = TestUtils.renderIntoDocument(); + + // Wait before changing the input + setTimeout(function () { + form.setProps({value: 'bar'}); + + forceUpdate(function () { + // Wait for next event loop, as that does the form + setTimeout(function () { + TestUtils.Simulate.submit(form.getDOMNode()); + expect(model.test).toBe('bar'); + done(); + }, 0); + + }); + + }, 10); + + }); + + it('should invalidate a valid form if dynamically inserted input is invalid', function (done) { var forceUpdate = null; diff --git a/src/main.js b/src/main.js index 5052552..a592979 100644 --- a/src/main.js +++ b/src/main.js @@ -160,6 +160,15 @@ Formsy.Mixin = { nextProps._validate = this.props._validate; }, + componentDidUpdate: function(prevProps, prevState) { + if (this.state._isPristine) { + if (this.props.value !== prevProps.value && this.state._value === prevProps.value) { + this.state._value = this.props.value || ''; + this.props._attachToForm(this); + } + } + }, + // Detach it when component unmounts componentWillUnmount: function () { this.props._detachFromForm(this);