Manipulating the checkbox value before saving to DB

default discord avatar
loaialsharee
2 months ago
3

I have an existing db that has a field

status

. This field currently holds a value either 0 or 1. I want to enable the user to toggle that value, however, since checkbox-type values are set to boolean (true or false). How can I use collection/field Hooks to manipulate the data so that if that field is updated using a checkbox, it is saved as either 0 or 1 - not true/false.



I tried using

beforeChange

&

beforeValidation

(collection-wise) but still cannot achieve what I want. Any ideas?

  • default discord avatar
    60pfennig
    2 months ago

    I would solve it propably by using a number field for your status. then swap in a custom component for that field which shows the default checkbox component (

    import { Checkbox } from "payload/components/forms";

    ) and the

    useField

    hook to set the numeric value according of the boolean state of the Checkbox component.

  • default discord avatar
    loaialsharee
    2 months ago

    @hendrik01 @60pfennig Thanks a lot to both of you. Your suggestions work for me as a charm!

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.