From 9ab0acff82685cc72ff25ec928729c892acc63fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Holas?= Date: Mon, 4 May 2015 22:22:05 +0200 Subject: [PATCH] Allow form to be initialised with specified data Modify reset function so that it accepts argument with data model that the form should be initialised with. This comes handy when you want to edit an object to have the form prefilled with object data by just passing the object to reset function instead of filling the fields manualy. --- src/main.js | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/main.js b/src/main.js index 4f978e2..8d96a98 100644 --- a/src/main.js +++ b/src/main.js @@ -50,7 +50,7 @@ Formsy.Form = React.createClass({ }, componentWillUpdate: function () { - + // Keep a reference to input keys before form updates, // to check if inputs has changed after render this.prevInputKeys = Object.keys(this.inputs); @@ -58,7 +58,7 @@ Formsy.Form = React.createClass({ }, componentDidUpdate: function () { - + if (this.props.validationErrors) { this.setInputValidationErrors(this.props.validationErrors); } @@ -70,9 +70,10 @@ Formsy.Form = React.createClass({ }, - reset: function () { + // Allow resetting to specified data + reset: function (data) { this.setFormPristine(true); - this.resetModel(); + this.resetModel(data); }, // Update model, submit to url prop and send the model @@ -104,10 +105,14 @@ Formsy.Form = React.createClass({ }.bind(this)); }, - // Reset each key in the model to the original / initial value - resetModel: function () { + // Reset each key in the model to the original / initial / specified value + resetModel: function (data) { Object.keys(this.inputs).forEach(function (name) { - this.inputs[name].resetValue(); + if (data && data[name]) { + this.inputs[name].setValue(data[name]); + } else { + this.inputs[name].resetValue(); + } }.bind(this)); this.validateForm(); },