|
var React = require('react'); |
|
var ReactDOM = require('react-dom'); |
|
var Formio = require('react-formio'); |
|
var Formiojs = require('formiojs'); |
|
|
|
var CalcForm = React.createClass({ |
|
getInitialState: function() { |
|
return { |
|
score: this.props.value || 0 |
|
}; |
|
}, |
|
calculate: function(submission) { |
|
let score = 0; |
|
var componentScore = function(component) { |
|
// Depending on the component type, find a value. Default to 0. |
|
let result = 0; |
|
|
|
// See if has a value class. Useful for checkboxes. |
|
if (submission.data.hasOwnProperty(component.key) && submission.data[component.key]) { |
|
// Find class with pattern "value000" |
|
if (component.hasOwnProperty('customClass')) { |
|
let regExp = new RegExp(/value(\d*)/, 'gi'); |
|
for (let className of component.customClass.split(' ')) { |
|
let matches = regExp.exec(className); |
|
if (matches) { |
|
result = Number(matches[1]); |
|
break; |
|
} |
|
}; |
|
} |
|
} |
|
|
|
// Component has a number value. |
|
if (!result && submission.data.hasOwnProperty(component.key) && !isNaN(submission.data[component.key])) { |
|
return Number(submission.data[component.key]); |
|
} |
|
|
|
return result; |
|
} |
|
this.form.components.forEach(function(component) { |
|
if (component.hasOwnProperty('components')) { |
|
let multiple = 1; |
|
// Find class with pattern "multiple000" |
|
if (component.hasOwnProperty('customClass')) { |
|
let regExp = new RegExp(/multiple(\d*)/, 'gi'); |
|
for (let className of component.customClass.split(' ')) { |
|
let result = regExp.exec(className); |
|
if (result) { |
|
multiple = result[1]; |
|
break; |
|
} |
|
}; |
|
} |
|
|
|
component.components.forEach(function(component) { |
|
score += componentScore(component) * multiple; |
|
}); |
|
} |
|
else { |
|
score += componentScore(component); |
|
} |
|
}); |
|
this.setState(function(previousState) { |
|
return previousState.score = score; |
|
}); |
|
}, |
|
componentDidMount: function() { |
|
// Load form definition so we can use it for calculations. |
|
if (this.props.src) { |
|
this.formio = new Formiojs(this.props.src); |
|
this.formio.loadForm().then((form) => { |
|
this.form = form; |
|
}); |
|
} |
|
}, |
|
render: function() { |
|
return ( |
|
<div> |
|
<h3>Score: { this.state.score }</h3> |
|
<Formio src={ this.props.src } onChange={ this.calculate }></Formio> |
|
</div> |
|
); |
|
} |
|
}); |
|
|
|
ReactDOM.render( |
|
<CalcForm src="https://examples.form.io/fieldtags"></CalcForm>, document.getElementById('formio') |
|
); |