Add editing capability to the List stock levels in WooCommerce plugin
Just two weeks ago I wrote code to display the stock level of every product and variation. Shortly after that I had a meeting with my client where we discussed the barcode scanning project. She asked what would happen if a product was mistakenly scanned twice (or more). I said that I would update the stock level page to allow for editing.
Progressive enhancement & incremental development
On submission I ensure that a valid product ID is submitted and that the new stock level is greater than 0. In both cases I cast the submitted data to an int to try to reduce any security holes. The wc_get_product() function does further error checking to ensure that the product ID corresponds to a valid product.
Although the form submits an “old_stock_count” number this is not used. I added for possible future use.
I recently started looking at CSS transitions and animation, compiling a small library of code snippets that I can use to liven up future projects.
After the form submission I wanted to highlight the updated product. I turned to a CSS animation – giving the appropriate row a flash where the background colour changes to a light green and then back to the previous colour. I add a class “updated” to product’s table row and the CSS animation takes care of the rest.
When the standard form code was finished I began adding the ajax submission feature. I used my AJAX script generator to create the starting code – there are a number of variables used in both the PHP and JS code and it’s easy to make a mistake.
I added a data attribute (“data-product-id“) to the Update button and retrieve this to submit. I added an ID to each table row so that I could retrieve the value of the input fields on that row.
On successful return I display a simple alert() listing the name of the product that has been updated and the new stock level.
I saw that the ajax code that verified the submitted data and updated the product stock level was almost identical to the form submission code. I refactored the code so that the ajax and form submission methods could use the same function. The wp_doing_ajax() function checks whether it’s an ajax or form submission.
Just like a cookery book should have lots of photos, everyone needs a screenshot to show the code in action.
And the updated PHP file:
For the ajax code I should add a full screen overlay with spinner so that the user doesn’t try to update another product while waiting for the update of the first one to complete (though it should still work).