Merge pull request #27 from sdemjanenko/update_pristine_values_on_model

Update form's model if the input is pristine and its value changes; test
This commit is contained in:
Christian Alfoni 2015-02-23 07:39:23 +01:00
commit bbc6ad38e2
2 changed files with 61 additions and 0 deletions

View File

@ -156,6 +156,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);