2016-05-02 15:08:45 +05:30
|
|
|
import FormInputComponent from './FormInputComponent';
|
2016-05-02 14:50:50 +05:30
|
|
|
|
2016-05-02 15:08:45 +05:30
|
|
|
export default class FormModel {
|
2016-05-01 12:48:34 +05:30
|
|
|
fields = {};
|
2016-05-02 14:50:50 +05:30
|
|
|
errors = {};
|
2016-05-01 12:48:34 +05:30
|
|
|
|
|
|
|
/**
|
|
|
|
* Connects form with React's component
|
|
|
|
*
|
|
|
|
* Usage:
|
|
|
|
* <input {...this.form.bindField('foo')} type="text" />
|
|
|
|
*
|
|
|
|
* @param {string} name - the name of field
|
|
|
|
*
|
|
|
|
* @return {Object} ref and name props for component
|
|
|
|
*/
|
|
|
|
bindField(name) {
|
2016-05-02 23:02:03 +05:30
|
|
|
this.fields[name] = {};
|
|
|
|
|
2016-05-02 14:50:50 +05:30
|
|
|
const props = {
|
2016-05-01 12:48:34 +05:30
|
|
|
name,
|
|
|
|
ref: (el) => {
|
2016-05-02 15:08:45 +05:30
|
|
|
if (el && !(el instanceof FormInputComponent)) {
|
|
|
|
throw new Error('Expected FormInputComponent component');
|
2016-05-02 14:50:50 +05:30
|
|
|
}
|
|
|
|
|
2016-05-01 12:48:34 +05:30
|
|
|
this.fields[name] = el;
|
|
|
|
}
|
|
|
|
};
|
2016-05-02 14:50:50 +05:30
|
|
|
|
|
|
|
if (this.getError(name)) {
|
|
|
|
props.error = this.getError(name);
|
|
|
|
}
|
|
|
|
|
|
|
|
return props;
|
2016-05-01 12:48:34 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
focus(fieldId) {
|
|
|
|
if (!this.fields[fieldId]) {
|
|
|
|
throw new Error(`The field with an id ${fieldId} does not exists`);
|
|
|
|
}
|
|
|
|
|
|
|
|
this.fields[fieldId].focus();
|
|
|
|
}
|
|
|
|
|
2016-05-01 23:20:55 +05:30
|
|
|
value(fieldId) {
|
2016-05-02 23:02:03 +05:30
|
|
|
const field = this.fields[fieldId];
|
|
|
|
|
|
|
|
if (!field) {
|
2016-05-01 23:20:55 +05:30
|
|
|
throw new Error(`The field with an id ${fieldId} does not exists`);
|
|
|
|
}
|
|
|
|
|
2016-05-02 23:02:03 +05:30
|
|
|
if (!field.getValue) {
|
|
|
|
return ''; // the field was not initialized through ref yet
|
|
|
|
}
|
|
|
|
|
|
|
|
return field.getValue();
|
2016-05-01 23:20:55 +05:30
|
|
|
}
|
|
|
|
|
2016-05-02 14:50:50 +05:30
|
|
|
setErrors(errors) {
|
|
|
|
const oldErrors = this.errors;
|
|
|
|
this.errors = errors;
|
|
|
|
|
|
|
|
Object.keys(this.fields).forEach((fieldId) => {
|
|
|
|
if (oldErrors[fieldId] || errors[fieldId]) {
|
|
|
|
this.fields[fieldId].setError(errors[fieldId] || null);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
getError(fieldId) {
|
|
|
|
return this.errors[fieldId] || null;
|
|
|
|
}
|
|
|
|
|
2016-05-01 12:48:34 +05:30
|
|
|
serialize() {
|
2016-05-02 14:50:50 +05:30
|
|
|
return Object.keys(this.fields).reduce((acc, fieldId) => {
|
|
|
|
acc[fieldId] = this.fields[fieldId].getValue();
|
2016-05-01 12:48:34 +05:30
|
|
|
|
|
|
|
return acc;
|
|
|
|
}, {});
|
|
|
|
}
|
|
|
|
}
|