sandy
sandy

Reputation: 103

How do I add checkboxes to admin-on-rest admin on rest create form and post the checkbox value to backend

I have added the material-ui/Checkbox component in admin-on-rest create form with source attribute. But after I click save button, I could not see the checkbox value in posted data.

But I can see 'title' and 'body' fields value in posted data. Can someone please tell, Why this code is not working?

Here is my sample code:

export const PostCreate = (props) => (
        <Create {...props} >
            <SimpleForm>
                <TextInput source="title" />
                <LongTextInput source="body" />
                <Checkbox
                    label="Label on the left"
                    labelPosition="left"
                    source="test"
                    value="yes"
                />
    </SimpleForm></Create>
    );

Upvotes: 0

Views: 1996

Answers (2)

MaxAlex
MaxAlex

Reputation: 3319

The BooleanInput.js module from rect-admin, Switch is replaced with Checkbox:

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import FormControlLabel from '@material-ui/core/FormControlLabel'
import FormGroup from '@material-ui/core/FormGroup'
import Checkbox from '@material-ui/core/Checkbox'
import { addField, FieldTitle } from 'ra-core'

const sanitizeRestProps = ({
  alwaysOn,
  basePath,
  component,
  defaultValue,
  formClassName,
  initializeForm,
  input,
  isRequired,
  label,
  locale,
  meta,
  options,
  optionText,
  optionValue,
  record,
  resource,
  allowEmpty,
  source,
  textAlign,
  translate,
  translateChoice,
  ...rest
  }) => rest

export class CheckboxInput extends Component {
  handleChange = (event, value) => {
    this.props.input.onChange(value)
  }

  render() {
    const {
      className,
      input,
      isRequired,
      label,
      source,
      resource,
      options,
      ...rest
    } = this.props

    return (
      <FormGroup className={className} {...sanitizeRestProps(rest)}>
        <FormControlLabel
          control={
            <Checkbox
              color="primary"
              checked={!!input.value}
              onChange={this.handleChange}
              {...options}
            />
          }
          label={
            <FieldTitle
              label={label}
              source={source}
              resource={resource}
              isRequired={isRequired}
            />
          }
        />
      </FormGroup>
    )
  }
}

CheckboxInput.propTypes = {
  className: PropTypes.string,
  input: PropTypes.object,
  isRequired: PropTypes.bool,
  label: PropTypes.string,
  resource: PropTypes.string,
  source: PropTypes.string,
  options: PropTypes.object,
}

CheckboxInput.defaultProps = {
  options: {},
}

export default addField(CheckboxInput)

Upvotes: 1

Dennie de Lange
Dennie de Lange

Reputation: 2934

Sure Checkbox is not a react-on-admin component. Please use BooleanInput

Upvotes: 3

Related Questions