4

I have a plugin that uploads and associates files/assets to users and entries. I would like it to store these files under a user ID subfolder of the asset folder. I know how to do this within the controlpanel, working with assets there. But how would I create and register subfolders within my plugin? If I just create the folder with my php script, it doesnt show up in the assets folder until i do a "Update Asset Indexes".

The way my plugin works now, It creates an asset with the craft()->assets->insertFileByLocalPath, and then associates the fileId with my entry after its created/uploaded. Maybe this is not the right way to do it?

Any help much appreciated.

2 Answers 2

3

I’ve had the problem with storeFolder() that it doesn’t create a folder that is accessible via the control panel or the file system.

I find createFolder() much easier to use and it did what I expected:

$response = craft()->assets->createFolder($parentFolderId, $folderName);
$folderId = $response->getResponseData()['folderId'];
1
  • This is the right way of doing things. This not only also calls the storeFolder method, but also checks for naming conflicts. Nov 28, 2016 at 20:34
1

To answer my own question, I found the answer in the source code.

$newFolder = new AssetFolderModel(
                array(
                    'parentId' => $currentFolderid,
                    'name' => $folderName,
                    'sourceId' => $currentFolderid,
                    'path' => trim($folderName, '/').'/'
                )
            );
            $folderId = craft()->assets->storeFolder($newFolder);

Basically you can specify a parentId, witch is the ID of the parent folder.

1
  • This is not the correct answer. Calling storeFolder just creates a folder in the database, not on the actual Asset source. @medoingthings has posted a much better way. Nov 28, 2016 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.