Search code examples
phpzend-frameworkzend-db-table

Zend Framework Update Checkboxes in Database


I have just started with Zend Framework, so might be a bit of a silly question coming up.

I have a Form with 5 Checkboxes. A User can click on as many checkboxes as needed. This gets entered into the Database. (1:n)

This all works fine. But now I am gotten to the part where a User can Edit the Post. The Checkbox gets shown as well as which once are active. But how do I update this now?

The Rest of the Post Update works fine, collecting the Data and send an update:

    $this->getDbTable()->update($data, array('post_id = ?' => $id));

Now I want to update the Checkboxes, the 1:n Relationship. But how would I do that if I for example had 4 Checkboxes active but after the update I want only 3 active? Should I delete all entries first and than do a normal insert or is there a trick to do it?

Hope someone can help. Thanks !


Solution

  • Assuming that the row existing in your database is what you use to indicate that it should be checked, you will need to delete it as the update() function won't do that.

    If delete / re-insert is going to be too expensive of an operation, perhaps store the checked values in the session and do an array_diff($previous_selected, $currently_selected) to get the list of items to delete.

    One thing to note is that the formCheckbox view helper by default creates a hidden input with the same name as the checkbox with a value of 0.