Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Manipulating the checkbox value before saving to DB

default discord avatar
loaialshareelast year
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
    60pfenniglast year

    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
    loaialshareelast year

    @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 dedicated engineering support directly from the Payload team..