UploadField - setFolderName sets Folder name to "NewPage" instead of page title

Silverstripe Version: 4.11

I use an UploadField and set a folder name (please see code below) . I want to set the folder name to the title of this page, but it seems the folder gets created as soon as the new page gets created, as the folder name is “NewPage” instead the name of the meeting. It actually creates a new folder with the page title once I changed the title of the new page and saved the newly created page, but with every new page I get a new “NewPage” folder that needs to be manually deleted.

How can I avoid the creation of the folder before the page is actually saved or can I set the folder structure afterwards somehow?

public function getCMSFields()
    {
        $fields = parent::getCMSFields();
...
       $fields->addFieldToTab('Root.Main', $upload = UploadField::create('FinalReport'), 'Content');
...
      $parentFolder = $this->MeetingCategory;

      $upload->setFolderName('Meetings/' . $parentFolder . '/' . $this->Title);
...
      return $fields;

    }

Thank you very much.

Hi, @Kimk

In silverstripe 3.1 it converts any underscores in the folder name into dashes. However, everytime subsequent files are uploaded, a new folder will be created on the filesystem with a numbered suffix ie. “new_folder” becomes “new-folder”, then after 3 more file uploads, folders “new-folder-2”, “new-folder-3” and “new-folder-4” will be created on the file system.

The only way to work around this is as a temporary solution is to convert all underscores to dashes before calling the setFolderName function. This then works as expected without creating a new folder with a numbered suffix everytime a new file is uploaded.

So, in the Page class you can do this change:

class Page extends SiteTree {
...
    public static function removeUnderscoreFromFolderName($folder_name) {
        return str_replace('_','-',$folder_name);
    }
}

then use the function as follows:

public function getCMSFields()
{
    $fields = parent::getCMSFields();
    ...
    $fields->addFieldToTab('Root.Main', $upload = UploadField::create('FinalReport'), 'Content');
    ...
    $parentFolder = $this->MeetingCategory;
    $upload->setFolderName(Page::removeUnderscoreFromFolderName('Meetings/' . $parentFolder . '/' . $this->Title));
    ...
    return $fields;
}