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.
This commit is contained in:
Stephen Demjanenko 2015-02-21 12:33:49 -08:00
parent 86ba085cc4
commit 03bc5a4079
2 changed files with 61 additions and 0 deletions

View File

@ -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 <input value={this.getValue()} onChange={this.changeValue}/>
}
});
var input;
var TestForm = React.createClass({
componentWillMount: function () {
forceUpdate = this.forceUpdate.bind(this);
},
onSubmit: function (formModel) {
model = formModel;
},
render: function () {
input = <TestInput name='test' value={ this.props.value } />;
return (
<Formsy.Form onSubmit={this.onSubmit}>
{input}
</Formsy.Form>);
}
});
var form = TestUtils.renderIntoDocument(<TestForm value='foo'/>);
// 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;

View File

@ -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);