1

Is there a way to have a button in a react-admin form so that when I click the button, the values are reset to the edited record's initial values?

I don't mean a Cancel button (that would close the form and redirect). I mean a reset-to-initial-values button that would discard any changes from the last save.

Thanasis Ioannidis
  • 2,981
  • 1
  • 30
  • 50

1 Answers1

2

New implementation related to replacing 'redux-form 'with' react-final-form':

import React, {
  useCallback,
} from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import { Button } from 'react-admin'
import { useForm } from 'react-final-form'
import { makeStyles } from '@material-ui/core/styles'
import IconClear from '@material-ui/icons/Clear'

const useStyles = makeStyles(theme => ({
  button: {
    marginLeft: '10px', 
    position: 'relative',
  },
  leftIcon: {
    marginRight: theme.spacing(1),
  },
  icon: {
    fontSize: 18,
  },
}), { name: 'ClearButton' })

const sanitizeRestProps = ({
  basePath,
  invalid,
  pristine,
  //reset,
  saving,
  submitOnEnter,
  handleSubmit,
  handleSubmitWithRedirect,
  undoable,
  onSave,
  ...rest
}) => rest

const ClearButton = ({ className, icon, ...rest}) => {
  const classes = useStyles()
  const form = useForm()

  const handleClick = useCallback(() => {
    form.setConfig('keepDirtyOnReinitialize', false)
    form.reset() 
    form.setConfig('keepDirtyOnReinitialize', true)
  }, [form])

  return (
    <Button
      className={classnames(classes.button, className)}
      onClick={handleClick}
      {...sanitizeRestProps(rest)}
    >
      { icon ? React.cloneElement(icon, { className: classnames(classes.leftIcon, classes.icon) }) : null }
    </Button>
  )
}

ClearButton.propTypes = {
  className: PropTypes.string,
  classes: PropTypes.object,
  icon: PropTypes.element,
}

ClearButton.defaultProps = {
  icon: <IconClear />,
  label: 'Clear',
}

export default ClearButton
MaxAlex
  • 2,919
  • 1
  • 14
  • 14
  • What would be the result of this reset? clearing all fields to empty values or setting their values to the last saved state of the record? – Thanasis Ioannidis Oct 16 '19 at 10:20
  • Setting values to the last saved state of the record – MaxAlex Oct 16 '19 at 10:29
  • works like a charm. Btw do you know how to execute code after a successful save? I have an edit form constantly open, and upon saving I want some of the fields to reset to empty values (mostly image uploads). – Thanasis Ioannidis Oct 16 '19 at 12:09
  • Try to keep the form so that all the fields after you save will be reset to the initial value:`` – MaxAlex Oct 16 '19 at 12:35