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'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.

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   2122 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!