Skip to content

Commit

Permalink
Merge pull request #16 from AgencyPMG/form_data
Browse files Browse the repository at this point in the history
Provide a Way for Callers to Access Form Data
  • Loading branch information
chrisguitarguy committed Feb 14, 2017
2 parents 557aa5c + 84a6ade commit 657851a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export default function higherform(fieldSpec, formSpec) {
...formData,
};
this.submit = this.submit.bind(this);
this.getData = this.getData.bind(this);
}

componentWillReceiveProps(nextProps) {
Expand Down Expand Up @@ -146,6 +147,25 @@ export default function higherform(fieldSpec, formSpec) {
}
}

/**
* Get a snapshot of the data currently held by the form.
*
* Any field that is not set will be undefined. The data returned
* here is not guaranteed to be valid.
*
* @return object
*/
getData() {
let out = {};
for (let f in this.fields) {
out[f] = typeof this.state[f] === 'undefined'
? void 0
: this.fields[f].filterOutput(this.state[f]);
}

return out;
}

buildFields() {
let out = {};
for (let field in this.fields) {
Expand All @@ -159,6 +179,7 @@ export default function higherform(fieldSpec, formSpec) {
return {
submit: this.submit,
errors: this.state.__errors,
getData: this.getData,
}
}

Expand Down
12 changes: 12 additions & 0 deletions test/form.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ describe('form', function () {
<form onSubmit={this.onSubmit.bind(this)}>
<input type={this.props.fieldType === 'input' ? 'text' : this.props.fieldType} {...fields.example.props()} />
{this._errors()}
{this._data()}
<button type="submit">Submit</button>
</form>
);
Expand All @@ -56,6 +57,17 @@ describe('form', function () {
</div>
);
}

_data() {
let fd = this.props.form.getData()


return (
<div className="form-data">
{Object.keys(fd).map((k, i) => <p key={i}>{k}: {JSON.stringify(fd[k])}</p>)}
</div>
);
}
}

describe('#FieldSpec(object)', function () {
Expand Down

0 comments on commit 657851a

Please sign in to comment.