Skip to content

Commit

Permalink
Adds "Form.clear" for clearing the fields
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Aug 20, 2018
1 parent 8828d9e commit aa119e8
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 19 deletions.
19 changes: 16 additions & 3 deletions src/components/Form.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -605,15 +605,28 @@ export default class Form extends React.Component {
return isFormValid;
}

/**
* Clears all the fields.
*/
clear = () => {
const nextFields = this.state.fields.map(fieldUtils.resetField(() => ''));
this.setState({ fields: nextFields });
}

/**
* Resets all the fields to their initial state upon mounting.
*/
reset = () => {
const nextFields = this.state.fields.map(fieldProps => fieldUtils.resetField(fieldProps));
const nextFields = this.state.fields.map(fieldUtils.resetField((fieldProps) => {
return fieldProps.get('initialValue');
}));

this.setState({ fields: nextFields }, () => {
/* Validate only non-empty fields, since empty required fields should not be unexpected on reset */
this.validate(entry => Map.isMap(entry) && (entry.get('value') !== ''));
/**
* Validate only non-empty fields, since empty required fields should
* not be unexpected upon reset.
*/
this.validate(fieldProps => Map.isMap(fieldProps) && (fieldProps.get('value') !== ''));

/* Call custom callback methods to be able to reset controlled fields */
const { onReset } = this.props;
Expand Down
37 changes: 21 additions & 16 deletions src/utils/fieldUtils/resetField.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,26 @@
* @param {Map} fieldProps
* @returns {Map}
*/
export default function resetField(fieldProps) {
/* Get the dynamic property name which represents the field's value (i.e. "checked" for Checkbox) */
const valuePropName = fieldProps.get('valuePropName');
const initialValue = fieldProps.get('initialValue');
export default function resetField(getNextValue) {
return (fieldProps) => {
/**
* Get the dynamic property name which represents the
* field's value (i.e. "checked" for Checkbox).
*/
const valuePropName = fieldProps.get('valuePropName');
const nextValue = getNextValue(fieldProps);

return fieldProps.merge({
[valuePropName]: initialValue,
expected: true,
valid: false,
invalid: false,
validating: false,
validated: false,
validSync: false,
validAsync: false,
validatedSync: false,
validatedAsync: false
});
return fieldProps.merge({
[valuePropName]: nextValue,
expected: true,
valid: false,
invalid: false,
validating: false,
validated: false,
validSync: false,
validAsync: false,
validatedSync: false,
validatedAsync: false
});
};
}

0 comments on commit aa119e8

Please sign in to comment.