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.

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

How to show latest files uploaded to folder or one of it's subfolders

Go to End

4 Posts   2498 Views


Community Member, 150 Posts

23 July 2011 at 4:14am

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.


Community Member, 545 Posts

23 July 2011 at 7:53am

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
					//push sub fodler list to folder list
			//loop through all foldes to find files
			foreach($folders as $folder){
				$file = DataObject::get("File", "ClassName != 'Folder' AND ParentID=".$folder->ID);
		$files->sort("Created", "DSC");//reverse sort by date created
		return $files->getRange(0,5);//return first five in list


Forum Moderator, 1391 Posts

24 July 2011 at 7:43am

Edited: 24/07/2011 7:44am

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 %>
	<% control NewPublicUploads %>
		<li><a href="$Filename">$Title.XML</a></li>
	<% end_control %>
<% end_if %>


Community Member, 150 Posts

24 July 2011 at 6:58pm

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 :)