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.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

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

SOLVED: Calling the first item in a many_many array


Go to End


3 Posts   1581 Views

Avatar
LinseyM

Community Member, 99 Posts

22 November 2011 at 8:56am

Hi,

I've customised the CMS so that the user can chosse multiple uploaded images to display in an image scroller using a treemultiselect field.

Done this as follows:


public static $many_many = array(
   "ChooseImages" => "File"
); 

function getCMSFields() {
   $fields = parent::getCMSFields();
   $fields->addFieldToTab('Root.Content.PhotoGallery', new TreeMultiSelectField('ChooseImages', 'Select images for gallery:', 'File'), '');
   return $fields;
}

this is then called in the template as:


<% control ChooseImages %><img src="$Link" border="0" height="110" width="167" ><% end_control %>

This works perfectly, and loads up every image that the user selected.

However if I only want to call the first item of the array (eg only access the first image that is selected) how do I do that? Assuming its a function, tried a few things but no success... eg in the page controller


class CoursePage_Controller extends Page_Controller {
	
	function GetFirstPic() {
		$a = ChooseImages[0];
		return ($a);
	}
}

Didn't really expect it to work, but worth a try! ;-)

Avatar
(deleted)

Community Member, 473 Posts

22 November 2011 at 10:19am

You could either use:

return $this-> ChooseImages()->First();

or, do it straight in your template with:

<% control ChooseImages.First %>$SetSize(167, 110)<% end_control %>

Avatar
LinseyM

Community Member, 99 Posts

22 November 2011 at 11:27am

Well, that was simple. Works perfectly. Thank you!