jabrij93's avatar

Database store checkbox input 'checked' to true/false but when updating or editing the form again, the checkbox isn't according to db

As the title suggest, when I want to edit the form again, the checkbox displayed no values although in database the values has been successfully stored. This confuses the user since as the user complete filling in the form and want to edit it back, the checkbox changed to unticked.

From my research, do I have to use hook useOptions ? doing something like const { activeOptions } = useOptions() ? I am not sure, my depth of knowledge in this topic is very limited but since I've got a project that need to completed asap(deadline is tomorrow), how can I make this work? The following are the code that I'm using right now.

<div className={'col-span-1'} >
              <InputLabel
                value={'Kata Laluan PDF'}
                className={'mb-2 font-bold text-base'}
                required={false}
              />
              <TextInput
                type={'checkbox'}
                name={'is_password'}
                className={''}
                value={data.is_password}
                handleChange={(e) => setData({ ...data, is_password: e.target.checked })}
              />
              <InputError message={errors.is_password}/>
      </div>

        <div className="col-span-1">
            <InputLabel
                value={"Stamping"}
                className={"mb-2 font-bold text-base"}
                required={false}  
            />
            <TextInput
            type={'checkbox'}
            name={''}
            className={''}
            value={data.is_stamping}
            handleChange={(e) => setData({ ...data, is_stamping: e.target.checked })}
            />
            <InputError message={errors.is_stamping} />
      </div>
0 likes
2 replies
LaryAI's avatar
Level 58

The issue is that the checkbox is not being checked when the form is being edited, even though the value is stored in the database. To fix this, you need to set the checked attribute of the checkbox based on the value from the database. You can do this by adding a ternary operator to the checked attribute of the TextInput component. Here's an example:

<TextInput
  type={'checkbox'}
  name={'is_password'}
  className={''}
  checked={data.is_password ? true : false}
  handleChange={(e) => setData({ ...data, is_password: e.target.checked })}
/>

In this example, the checked attribute is set to true if data.is_password is truthy, and false otherwise. You can do the same for the other checkbox as well.

Note: If the data.is_password value is not a boolean, you may need to convert it to a boolean before using it in the ternary operator. You can do this using the double negation operator (!!). For example:

checked={!!data.is_password ? true : false}
jabrij93's avatar

This time, Larry A.I didn't get it right.. any laracasters can help me ?

1 like

Please or to participate in this conversation.