Xety/Cake3-Upload

:id path placeholder can't be used when creating new record.

Closed this issue · 7 comments

Since the entity's id would not be available when creating a new record one can't use the placehoder ":id" since the file is being saved in beforeSave(). In all your test cases you use an entity with id set so this case isn't covered.

Xety commented

Hello @ADmad,

Yes i know this issue, but i don't know how i can resolve it. I think i have 3 choices :

  • Tell to the user that this identifier is only for updating an entity
  • Remove this identifier
  • Rewrite all the behavior and use the afterSave() callback

Maybe you have a better solution to not rewrite all the behavior ?

For now I would go with option 2 and remove the identifier. If / when you have the time to refactor to only set the field value in beforeSave but do the actual file saving in afterSave() you can reinstate the identifier. Haven't really thought about the possible issues with doing so though.

Is #3 the solution to this?

solution option: use UUIDs so that they can be created when the upload form loads with String::uuid()
i think this is the only way other than afterSave()
see http://stackoverflow.com/questions/14731105/cakephp-need-to-know-model-id-before-saving

here's another possible solution: manually find the current highest ID in the system, and add one to it.

$id = 'unknown_id';
if($entity->id) {
    $id = $entity->id;
} else {
    $table = TableRegistry::get($entity->source());
    $query = $table->find();
    $maxId = $query->select(['max_id' => $query->func()->max('id')])->first()->max_id;
    if (is_numeric($maxId)) {
        $id = (int)$maxId + 1;
    }
}

$identifiers = [
    ':id' => $id,
    ...

Yes, there are downsides:

  • extra database hit required
  • risk of cross-contamination with concurrent saves

Warn the user about those drawbacks, and let them choose if they're willing to accept those drawbacks for the convenience of not having tons of files in a directory called unknown_id.

Xety commented

Hey,

Just to give some news, i will rewrite the plugin in the next weeks.
I'm actually working on a big project (Using Cake3 of course :)) since 8 months who will ended soon, so i will get the time to work on my plugins again.

Xety commented

There we go : #14 .