Andrew Plummer - Design Development Translation

Example 12: Using Callback to Update Files on a Server

Summary

Sometimes when working with databases it is not enough to update the data itself – you must perform other actions every time the data changes. Filenames are a very good example of this, since they are references to real files on the server. If you were to edit the name of a file, you would also have to rename the actual file on the server as well, or the reference would be broken. This is where callback comes in handy.

Example

View Example

PHP Code

function renameThumbnail($key, $previous, $updated, $ref){ $old = $previous["thumbnail"]; $new = $updated["thumbnail"]; if(file_exists($old) && !file_exists($new) && $old != $new){ rename($old, $new); } } $tg = new TableGear(array( "database" => array( "username" => "USERNAME", "password" => "PASSWORD", "database" => "DATABASE", "table" => "TABLE" ), "sortable" => "all", "editable" => "all", "loading" => array( "tag" => "img", "attrib" => array( "src" => "/images/icons/loading.gif", "alt" => "Loading", "class" => "loading" ) ), "formatting" => array( "price" => "currency[prefix=$,pad], "date" => "date" ), "totals" => array("price", "quantity"), "callback" => array( "onUpdate" => "renameThumbnail", "getPrevious" => true ) );

To be able to apply our callback function, we must define it outside the TableGear constructor and pass it in as a reference of type string. The function itself receives 4 arguments – we need $previous and $updated to find the old and new filenames. Once we have these we can rename the file.

Note that we need to pass a special parameter, getPrevious, so that our $previous object is filled with data from the previous row and we can get our old filename. For more information about callback, see the documentation.