If you tried clicking on the Add New Bug link created in the previous recipe, you would have been presented with a page that only contained the panel's title. This is due to the fact that we had not implemented the code to display a bug creation and editing form when the id variable is present in the website address.
The first few steps of this recipe aim to rectify this by checking for the presence of a variable called id in the page URL with a value set to the text new or a numeric value.
While both of these situations will result in displaying a bug edition form, the second condition first performs a database query using the wpdb object's get_row method to try to retrieve a bug with the designated ID. The get_row method is similar to the get_results method used in the previous recipe, but will only return a single row, even if more than one result is found by the query. As part of our get_row call, we also use the $wpdb class's prepare method. This method will parse the second argument it receives for security and then use it to replace the placeholder placed in our query. If the query is successful, the values that were retrieved are used to customize the form title and set initial field values.
The form itself is a standard HTML form that includes many of the elements that we have seen in previous recipes, such as a call to wp_nonce_field to provide security from external attacks. We have also added a hidden field containing the bug ID that was found in the page URL to facilitate data processing when a bug is submitted.
Once the form is in place, we make a call to add_action to register a callback that will be executed when the newly created form is submitted.
The callback, named process_ch8bt_bug, starts off by doing a bit of validation. Namely, it checks to see whether the current user has administrative rights and if the nonce field that should be part of the form data is present. If both of these conditions are met, a data array is created from user post data, the current system date, and a hardcoded status value.
The resulting array is stored in the website database using one of two wpdb object methods, insert or update, based on the value found in the hidden bug_id field. Both methods expect to receive the name of the target table, along with an associative array containing the names and values of each table field to be stored. Additionally, the update method requires a third parameter that indicates the field name and value to be used to locate the field to be updated. In both cases, you will notice that the bug_id field is not specified in the array of new values, since it gets automatically set to an incremental value by the database server.
The last step in this function is to build a clean URL to the plugin configuration page and use the resulting address in a call to wp_redirect.