SOLVED: “Remove image”-bug in AppGini > 5.9x – hooks-only solution

For some time there have been problems with deleting uploaded images. The bug seems to be still present in AppGini version 5.97. In this article I show a small help function to fix this problem.

In the AppGini Forum a solution is shown which requires the modification of the files TABLENAME_dml.php. However, changes in these files are overwritten the next time they are generated. Here I show a solution that uses only hooks, which remain in place the next time they are generated.

Problem

In the past, uploaded images could be deleted by clicking the Remove image checkbox and then saving the record. Due to a bug in AppGini generated code this still does not work in latest version 5.97, as you can see here:

The image remains. This affects both, the database table and the file system.

Solution

Step 1

Copy & Paste the following function in a central place, for example in hooks/__global.php:

// file: hooks/__global.php
function remove_image_hack($tn, $field, &$data)
{
  $pk = $data["selectedID"] ?? $data[getPKFieldName($tn)] ?? null;
  $key = "{$field}_remove";
  if (isset($_REQUEST[$key]) && $_REQUEST[$key] == "1" && $pk) {
    $fn = existing_value($tn, $field, $pk);
    if ($fn) {
      $dir = getUploadDir('');
      $ft = pathinfo($fn, PATHINFO_FILENAME);
      $fe = pathinfo($fn, PATHINFO_EXTENSION);
      foreach (["", "_tv", "_dv"] as $key => $suffix) @unlink("{$dir}{$ft}{$suffix}.{$fe}");
      $data[$field] = null;
    }
  }
  return TRUE;
}

Note: If you are using an outdated PHP version prior to PHP 7, there may be problems in line 4, starting with $pk = ... . In these cases, you can use the following legacy replacement:

$pk = $data["selectedID"] ? $data["selectedID"] : ($data[getPKFieldName($tn)] ? $data[getPKFieldName($tn)] : null);

Step 2

For each table containing images, open the PHP hook file, find the TABLENAME_before_update(...) function and add the following line of code per image-field:

function TABLENAME_before_update(&$data, $memberInfo, &$args) {
    return remove_image_hack("TABLENAME", "FIELDNAME", $data);
}

Example

In my case, tablename is employees and fieldname is image. So, my code looks like this:

function employees_before_update(&$data, $memberInfo, &$args)
{
    return remove_image_hack("employees", "image", $data);
}

That's it. Repeat this line for every problematic image field, if you have more than one in that table.

Result

Here is the result, it works as expected, now:

Summary

I'm pretty sure the bug will be fixed with one of the next versions. Anyway, if you, like me and my customers, need a soIution immediately, this function should help you.

Do you like it?