-
Notifications
You must be signed in to change notification settings - Fork 479
/
FormController.jsx
495 lines (446 loc) · 13.3 KB
/
FormController.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
import React, {PropTypes} from 'react';
import $ from 'jquery';
import {
Button,
Alert,
FormGroup,
Pagination,
} from 'react-bootstrap';
import i18n from '@cdo/locale';
const styles = {
pageButtons: {
verticalAlign: 'middle',
margin: '0 10px'
}
};
/**
* Helper class for dashboard forms. Expects to be extended by a class which
* will implement the getPageComponents method, which is expected to return an
* array of components with extend from the FormComponent helper class.
* Resulting form will then display those components paginated and in order,
* with a submit button on the last page.
*
* @see FacilitatorProgramRegistration component for example usage.
*/
export default class FormController extends React.Component {
constructor(props) {
super(props);
if (this.constructor === FormController) {
throw new TypeError(`
FormController is an abstract class; cannot construct instances directly
`);
}
this.state = {
data: {},
errors: [],
errorMessages: {},
errorHeader: null,
globalError: false,
currentPage: 0,
submitting: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.nextPage = this.nextPage.bind(this);
this.prevPage = this.prevPage.bind(this);
}
componentWillMount() {
if (this.constructor.sessionStorageKey && sessionStorage[this.constructor.sessionStorageKey]) {
const reloadedState = JSON.parse(sessionStorage[this.constructor.sessionStorageKey]);
this.setState(reloadedState);
}
}
/**
* @override
*/
componentWillUpdate(nextProps, nextState) {
// If we got new errors, navigate to the first page containing errors
if (this.state.errors.length === 0 && nextState.errors.length > 0) {
for (let i = 0; i < this.getPageComponents().length; i++) {
if (this.pageHasError(i, nextState.errors)) {
nextState.currentPage = i;
break;
}
}
}
}
/**
* @override
*/
componentDidUpdate(prevProps, prevState) {
// If we got new errors or just changed pages, scroll to top of the page
const newErrors = prevState.errors.length < this.state.errors.length;
const newPage = prevState.currentPage !== this.state.currentPage;
if (newErrors || newPage) {
$('html, body').animate({
scrollTop: 0
}, 200);
}
}
/**
* Method to be overridden by inheriting classes; will define the pages of
* this form by FormComponent instances.
*
* @returns {[FormComponent]}
*/
getPageComponents() {
throw new TypeError('must override FormController.getPageComponents');
}
/**
* @returns {FormComponent}
*/
getCurrentPageComponent() {
return this.getPageComponents()[this.state.currentPage];
}
/**
* Expects an object whose keys are the names of form inputs and whose values
* reflect the new expected state of those inputs; intended to match the
* format of the onChange handlers of ButtonList and FieldGroup
*
* @param {Object} newState
*/
handleChange(newState) {
// clear any errors for newly changed fields
const newFields = Object.keys(newState);
const errors = this.state.errors.filter(error => !newFields.includes(error));
// update state with new data
const data = Object.assign({}, this.state.data, newState);
this.setState({
data,
errors
});
this.saveToSessionStorage({data});
}
/**
* Override in derived classes with a key name (e.g. the class name)
* to save session storage in that key. Otherwise, no session storage will be saved.
*/
static sessionStorageKey = null;
/**
* Save currentPage and form data to the session storage, if a sessionStorageKey is specified on this class
* @param {Object} newState - data and/or currentPage to override the value in this.state
*/
saveToSessionStorage = (newState) => {
if (this.constructor.sessionStorageKey) {
const mergedData = {
...{
currentPage: this.state.currentPage,
data: this.state.data
},
...newState
};
sessionStorage.setItem(this.constructor.sessionStorageKey, JSON.stringify(mergedData));
}
};
/**
* Assemble all data to be submitted
*
* @returns {Object}
*/
serializeFormData() {
return {
form_data: this.state.data,
};
}
/**
* Called when we get a successful response from the API submission
*/
onSuccessfulSubmit() {
// Intentional noop; overridden by child classes
}
/**
* Submit serialized form data to the specified API Endpoint and handle server
* response
*
* @param {Event} event
*/
handleSubmit(event) {
event.preventDefault();
if (!this.validateCurrentPageRequiredFields()) {
return;
}
// clear errors so we can more clearly detect "new" errors and toggle
// submitting flag so we can prevent duplicate submission
this.setState({
errors: [],
errorHeader: null,
globalError: false,
submitting: true
});
$.ajax({
method: "POST",
url: this.props.apiEndpoint,
contentType: "application/json",
dataType: "json",
data: JSON.stringify(this.serializeFormData())
}).done(data => {
sessionStorage.removeItem(this.constructor.sessionStorageKey);
this.onSuccessfulSubmit(data);
}).fail(data => {
if (data.responseJSON &&
data.responseJSON.errors &&
data.responseJSON.errors.form_data) {
if (data.responseJSON.general_error) {
this.setState({
errors: data.responseJSON.errors.form_data,
errorHeader: data.responseJSON.general_error,
globalError: true
});
} else {
// if the failure was a result of an invalid form, highlight the errors
// and display the generic error header
this.setState({
errors: data.responseJSON.errors.form_data,
errorHeader: i18n.formErrorsBelow()
});
}
} else {
// Otherwise, something unknown went wrong on the server
this.setState({
globalError: true,
errorHeader: i18n.formServerError()
});
}
this.setState({
submitting: false
});
});
event.preventDefault();
}
/**
* @returns {Element|undefined}
*/
renderErrorFeedback() {
const shouldShowError = this.state.errorHeader &&
(this.state.globalError || this.pageHasError());
if (shouldShowError) {
return (
<Alert bsStyle="danger">
<h3>{this.state.errorHeader}</h3>
</Alert>
);
}
}
/**
* Determines if a given page (defaults to current page) is responsible for any
* of the given errors (defaults to current state errors).
*
* Note that for purposes of page errors, error strings like
* "fieldName[some_extra_data]" will be normalized to "fieldName"
*
* @param {number} [page=this.state.currentPage] which page to examine
* @param {String[]} [errors=this.state.errors] which errors to consider
*
* @returns {boolean}
*/
pageHasError(page=this.state.currentPage, errors=this.state.errors) {
const pageFields = this.getPageComponents()[page].associatedFields;
if (!pageFields) {
throw new TypeError(`
Every PageComponent of a FormController must define an array
PageComponent.associatedFields for error handling
`);
}
// When using VariableFormGroups that allow for nesting questions, the
// errors returned from the server can include state-specific data like
// "howInteresting[facilitator_name]". This is great for being able to flag
// the specific question on the page, but for purposes of determining which
// page a given error is on we really only care about the "howInteresting"
// key, not the "facilitator_name" data.
const flattenedErrors = errors.map(e => e.replace(/\[[^\]]*\]/, ''));
return pageFields.some(field => flattenedErrors.includes(field));
}
/**
* @returns {Object}
*/
getPageProps() {
return {
key: this.state.currentPage,
options: this.props.options,
onChange: this.handleChange,
errors: this.state.errors,
errorMessages: this.state.errorMessages,
data: this.state.data
};
}
/**
* @returns {Element}
*/
renderCurrentPage() {
const PageComponent = this.getCurrentPageComponent();
return (
<PageComponent
{...this.getPageProps()}
/>
);
}
/**
* Getter method for required field validation, so that inheriting classes can
* support conditionally-required fields
* @returns {String[]}
*/
getRequiredFields() {
const requiredFields = [...this.props.requiredFields];
const pageRequiredFields = this.getPageComponents().map(page => page.getDynamicallyRequiredFields(this.state.data));
return pageRequiredFields.reduce((flattened, subArray) => flattened.concat(subArray), requiredFields);
}
/**
* checks the data collected so far against the required fields and the fields
* for this page, to make sure that all required fields on this page have been
* filled out. Flags any such fields with an error, and returns a boolean
* indicating whether any were found.
*
* @return {boolean} true if this page is valid, false if any required fields
* are missing
*/
validateCurrentPageRequiredFields() {
const currentPage = this.getCurrentPageComponent();
const requiredFields = this.getRequiredFields();
const pageFields = currentPage.associatedFields;
// Trim string values on page, and set empty strings to null
let pageData = {};
pageFields.forEach(field => {
let value = this.state.data[field];
if (typeof value === "string") {
const trimmedValue = value.trim();
pageData[field] = trimmedValue.length > 0 ? trimmedValue : null;
} else {
pageData[field] = value;
}
});
pageData = Object.assign(pageData, currentPage.processPageData(pageData));
this.setState({
data: {
...this.state.data,
...pageData
}
});
const pageRequiredFields = pageFields.filter(f => requiredFields.includes(f));
const missingRequiredFields = pageRequiredFields.filter(f => !pageData[f]);
const formatErrors = currentPage.getErrorMessages(pageData);
if (missingRequiredFields.length || Object.keys(formatErrors).length) {
this.setState({
errors: [...missingRequiredFields, ...Object.keys(formatErrors)],
errorMessages: formatErrors,
errorHeader:
"Please fill out all required fields. You must completely fill out this section before moving \
on to the next section or going back to edit a previous section."
});
return false;
}
return true;
}
/**
* switch to the next page in sequence, if it exists
*/
nextPage() {
this.setPage(this.state.currentPage + 1);
}
/**
* switch to the previous page in sequence, if it exists
*/
prevPage() {
this.setPage(this.state.currentPage - 1);
}
/**
* switch to the specified page in sequence, if it exists
*/
setPage(i) {
const newPage = Math.min(
Math.max(i, 0),
this.getPageComponents().length - 1
);
const currentPageValid = this.validateCurrentPageRequiredFields();
if (currentPageValid) {
this.setState({
currentPage: newPage
});
this.saveToSessionStorage({currentPage: newPage});
}
}
/**
* @returns {boolean}
*/
shouldShowSubmit() {
return this.state.currentPage === this.getPageComponents().length - 1;
}
static submitButtonText = i18n.submit();
/**
* @returns {Element}
*/
renderControlButtons() {
let backButton;
if (this.state.currentPage > 0) {
backButton = (
<Button
key="back"
id="back"
onClick={this.prevPage}
>
Back
</Button>
);
}
let nextButton = (
<Button
bsStyle="primary"
key="next"
id="next"
onClick={this.nextPage}
>
Next
</Button>
);
if (this.shouldShowSubmit()) {
nextButton = (
<Button
bsStyle="primary"
disabled={this.state.submitting}
key="submit"
type="submit"
>
{this.constructor.submitButtonText}
</Button>
);
}
const pageButtons = (
this.getPageComponents().length > 1 &&
<Pagination
style={styles.pageButtons}
items={this.getPageComponents().length}
activePage={this.state.currentPage + 1}
onSelect={i => this.setPage(i - 1)} // eslint-disable-line react/jsx-no-bind
/>
);
return (
<FormGroup className="text-center">
{backButton}
{pageButtons}
{nextButton}
</FormGroup>
);
}
/**
* @override
*/
render() {
return (
<form
ref={form => {this.form = form;}}
onSubmit={this.handleSubmit}
>
{this.renderErrorFeedback()}
{this.renderCurrentPage()}
{this.renderControlButtons()}
</form>
);
}
}
FormController.propTypes = {
apiEndpoint: PropTypes.string.isRequired,
options: PropTypes.object.isRequired,
requiredFields: PropTypes.arrayOf(PropTypes.string).isRequired
};
FormController.defaultProps = {
requiredFields: []
};