I have a data object DocumentGroup and whenever I add a DocumentGroup I want to create an asset folder accordingly. How can I achieve that?
Currently it is set up to when once a Document (another data object) is added to the folder, the folder gets created, but now I need it to create the folder without the need of immediately uploading a file, but as soon as the DocumentGroup gets created. Is there a way?
I fail to see any sane reason for creating an empty folder, but if you need you can use Filesystem::makeFolder. Also, there is no shame in directly using plain PHP itself: the Silverstripe API uses it anyway, just recursively.
Hi ntd,
It is about forcing users to use a certain folder structure instead of every user creating their own version of folder structure/naming as happened in the past. It is about consistency.
I’m assuming by “asset folder” you mean a folder in the silverstripe CMS assets area? I.e. a SilverStripe/Assets/Folder?
You can create a new Folder any time a new DocumentGroup is written to the database by adding an onBeforeWrite() method to the DocumentGroup class which looks something like this:
public function onBeforeWrite()
{
parent::onBeforeWrite();
$folder = Folder::create(['Title' => 'Some Random Folder']);
$folder->write();
}
Disclaimer: I haven’t tested that code, so some alteration may be necessary.
Just to add to the above, to prevent creating a new folder each time (with -v2, -v3 etc) try wrapping with isInDB:
public function onBeforeWrite()
{
parent::onBeforeWrite();
if (!$this->isInDB()) {
$folder = Folder::create(['Title' => 'Some Random Folder']);
$folder->write();
}
}
Or you could use Folder::find_or_make('Path/To/Folder')
@kaftka thanks especially for the " Folder::find_or_make('Path/To/Folder')" as this would have been my next question regarding how to set a folder path. Now I know
I have another question which is kind of the opposite, so I will open a new question for this.