1

I created a custom field type to show user groups in a checkbox layout, e.g. (http://cl.ly/image/0A1a140m031h).

I am running into one small issue. If I add content with a checkbox(s) option selected and save the entry. Then I try to edit the entry and uncheck all the options, the entry will still have the original checkbox options selected and won't return to the null state as expected. I was trying to use prepValueFromPost but that doesn't seem to run unless the value is set. How do I fix this?

2 Answers 2

1

This isn't really an answer. But I think I do know what might be happening. The default browser behavior is that checkbox values only get submitted when it has the attribute 'checked' (why? I have no idea). In php you're essentially testing whether the post value exists or not. If it exists, true; if not, false. I assume for the built-in checkbox fieldtype that craft does this for you in the background (by somehow comparing with the original options). You'll have to figure out a way to perform this check yourself. Maybe take a look at the source files and see how craft is handling this.

2
  • If I recall, we add a hidden input for each checkbox that has an actual 0 or 1 value.
    – Brad Bell
    Jan 20, 2015 at 18:32
  • Thanks, I figured that could be an approach, a hidden field, but wasn't sure if there was a better route. I was able to resolve the issue.
    – mz91184
    Jan 20, 2015 at 23:23
1

If it helps anyone else, if you have a checkbox field in Craft with multiple options, you can use the hidden field approach with a value of [].

For example, two checkboxes, one with value="newsletter" and another with value="events", both with name="marketing[].

Then include a hidden field above them with value="[]" and name="marketing".

Important to leave off the [] from the hidden field's name.

This will mean that if no checkboxes are checked, it will set all of them to null/unchecked in Craft. However, as soon as any are checked, they will overwrite the hidden field safely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.