Checkbox form field type
From Joomla! Documentation
Revision as of 05:28, 30 January 2013 by E-builds
Saving checkbox problem
Special care needs to be taken with saving an unchecked checkbox from a form!! This is a common mistake for component developers thinking Joomla takes care of this. Joomla doesn't, until now. (Problem in Joomla 2.5 still.)
You see, on saving a form with a checkbox that is unchecked, there is no variable for it in the POST data! So, it's quite common that the value will NOT be overwritten in your DB, especially if it is already on the value that represents "checked" (e.g. 1 ) on the form.
My preference goes to Method 2 until Joomla developers acknowledge this problem.
Method 1: Use Jtable bind() override...
..and set possible not set checkbox variables to it's empty values.
Problem: It's a mess if the table is also used by other forms or component handling that don't offer that checkbox! (This time it will set the value to its empty value, but is not asked!)
Even the updateNulls and Jtable defaults workaround gives the same problem: Setting default variable to it's empty value (e.g. 0) in your table is also not a valid solution for this method because we would have to make updateNulls default to true on saving and that is not always desired for the same reason as above, that this table might be used by other code in your component. That an other reasons with null and 0 and so on...
Put one in the form before the checkbox (with the same name and the empty checkbox value), which the checkbox will override if it's checked. E.g.
<input type="hidden" name="jform[name]" value="0">
Not the nicest solution, but it works and evades a lot of other problems.
Method 3: Check checkboxes in your model somewhere
Since the model is more directly related to a specific form, this is a better place to set the empty checkbox instead of in the table.
Problem: Sometimes even the model can be reused and does not always use the same form.
Method 4: Check checkboxes in Joomla form code
Since the form is the only one that knows if a checkbox was present or not before saving it, it's the place to set the checkbox to the concurrent empty value if it is not set (=not in post data).
A component developer can overwrite the one or other form class, but that's not very nice, so I believe Joomla developers might better do this as an improvement to the joomla form code. Not sure where best to do that, but some guesses: while validating the form, in the checkbox field type, ..