Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Renaming a file after it was uploaded


Go to End


1611 Views

Avatar
smares

Community Member, 25 Posts

24 April 2012 at 12:03am

Hey guys, I am trying to figure out how to rename a file after it has been uploaded.

I have a custom DataObject with a property called "ProductID" and a has_one relation to Image called "Icon". This DataObject is managed by a CTF and the getCMSFields returns (among other fields) an ImageField. What I want to do is when the user saves the DataObject and an icon is attached, it should have the product ID as name.

After chatting on IRC, I tried to write the following in the onBeforeWrite method:

parent::onBeforeWrite();

$this->Icon()->Name = '123.' . $this->Icon()->Extension;
$this->Icon()->write();

The "123" is just a dummy. What happens is when the user selects an image from his computer and clicks on Attach image, two DB entries are created, for the file. One having "123." as filename and being in the root of the assets folder, and one having the original filename being in the directory specified in the ImageField. When the user clicks on "Save", the DB entry with the original filename is changed to reflect my desired "123.png" filename, however, the entry from the assets root "123." is still there. If I go to Files & Images and click on "Look for new files", that entry is removed.

Any idea how I am supposed to rename files the right way?