Manipulating the checkbox value before saving to DB

default discord avatar
loaialsharee8 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
    60pfennig8 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
    loaialsharee8 months ago

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

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

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