How can I show latest 5 files uploaded to a certain folder 'Public' OR uploaded to a subfolder of 'Public' OR uploaded to a subfolder of a subfolder of 'Public' and so on. Kind of like getChildrenAsUl, but than without the UL and LI and with a sort and limit function.
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.
Okay here's an idea. It seems a little clunky to me and only offers two levels of recursion. but it'll work. I've tested it on a system with over 10000 files, its a little slow but it works. Maybe someone can find a way to make it more elegant/faster
function LatestFiles() {
//Use the ID for your "Public" folder for ParentID
$files = new DataObjectSet();
$folders = DataObject::get("Folder", "ParentID = X");
if($folders) {
//loop through folders
foreach($folders as $folder){
//check if folder has sub-folder
if ($folder->hasChildFolders()){
//get sub fodlers
$subFolders = $folder->ChildFolders();
//loop through sub folders
foreach($subFolders as $subFolder) {
//check if has sub-sub folder
if ($subFolder->hasChildFolders()){
//get sub-sub folder
$subSubFolders = $subFolder->ChildFolders();
//push sub-sub folders to subfolder list
$subFolders->merge($subSubFolders);
}
}
//push sub fodler list to folder list
$folders->merge($subFolders);
}
}
//loop through all foldes to find files
foreach($folders as $folder){
$file = DataObject::get("File", "ClassName != 'Folder' AND ParentID=".$folder->ID);
$files->merge($file);
}
}
$files->sort("Created", "DSC");//reverse sort by date created
return $files->getRange(0,5);//return first five in list
}
Since the File table already 'knows' the path to each file in /assets/, in this case a straight query might get you there as well. Something like:
function NewPublicUploads() {
return DataObject::get(
$name = 'File',
$filter = "ClassName = 'file' and Filename like 'assets/public/%'",
$sort = "Created DESC",
$join = "",
$limit = "5"
);
}
<% if NewPublicUploads %>
<ul>
<% control NewPublicUploads %>
<li><a href="$Filename">$Title.XML</a></li>
<% end_control %>
</ul>
<% end_if %>
So simple... I guess I was trying to do it the hard way :) Many thanks Martimiz (and also zenmonkey; in this case I'll rate your answer as second-best :)