Search code examples
javascriptreactjsadmin-on-rest

Checkboxes checked by default


I'm using CheckboxGroupInput in a field with many checkboxes, and I'd like them to be checked by default.

I tried using the options attribute like this:

<CheckboxGroupInput source="foo" choices={[
  { id: 0, name: 'bar' },
  { id: 1, name: 'bar' }
]} options={{
  checked: true
}}/>

But no luck, all checkboxes are checked by default, but they are not usable: they can't be unchecked nor are sent in the POST/PUT request.

Thanks!

PS: A check all button also could be nice, if someone has implemented one I'd be happy to see how it was done.


Solution

  • You should use defaultValue on the form including this input.

    About the Check all button, this can be implemented in a custom input. You might copy/paste the code of the CheckboxGroupInput and implement the logic in it.

    About converting back the values into numbers, use the normalize prop:

    <CheckboxGroupInput
        normalize={value => value.map(v => parseInt(v, 10))}
        source="notifications"
        choices={[
            { id: 12, name: 'Ray Hakt' },
            { id: 31, name: 'Ann Gullar' },
            { id: 42, name: 'Sean Phonee' },
        ]}
    />