Created
August 6, 2018 22:23
-
-
Save jordangarcia/182dbdc002305f7c68bf922bee5c079b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import { Input, Button } from 'optimizely-oui' | |
import SectionModule from '../../section_module/'; | |
@Form({ | |
// Populates the form HoC with initial state for the entity being edited | |
// accessible via `props.formState.clean` and `props.form.state.editing` | |
initialStateGetter: SectionModule.getters.currentlyEditingExperiment, | |
}) | |
class MyForm extends React.Component { | |
constructor(props) { | |
super(props); | |
// global validation functino | |
// form {FormInterface} is passed to wrapped component as prop | |
const { form } = this.props; | |
form.addValidationFn({ | |
keypath: 'name', | |
getErrors(val) { | |
// these should be composable | |
let hasError | |
if (val.length === 0) { | |
return { | |
hasError: true, | |
details: { | |
message: 'Name is required', | |
} | |
} | |
} | |
if (val.length > 63) { | |
return { | |
hasError: true, | |
details: { | |
message: 'Name must be less than 64 characters', | |
} | |
} | |
} | |
return { | |
hasError: false, | |
details: {}, | |
} | |
}, | |
}) | |
} | |
handleSave = () => { | |
const { form } = this.props; | |
// this call will populate errors and pass them through props to the child components | |
// Question: should this return something? | |
form.validateAll(); | |
if (!form.isFormValid()) { | |
// you can also use this display global errors | |
return; | |
} | |
const data = form.getValue().toJS(); | |
// do save operation with data | |
} | |
render() { | |
const { | |
form, | |
formState, | |
} = this.props; | |
const nameField = form.field('name'); | |
return ( | |
<form> | |
<p> | |
is dirty: | |
<strong> | |
{ formState.isDirty ? 'true': 'false' } | |
</strong> | |
</p> | |
<Input | |
value={ nameField.getValue() } | |
onChange={ (e) => nameField.setValue(e.target.value) } | |
errors={ nameField.getErrors() } | |
/> | |
<div> | |
<Button | |
isDisabled={ !formState.isDirty } | |
onClick={ form.revert }> | |
Revert | |
</Button> | |
<Button | |
onClick={ this.handleSave }> | |
Save | |
</Button> | |
</div> | |
</form> | |
) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment