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.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Generate array for GroupedDropdownField


Go to End


2 Posts   2662 Views

Avatar
JackAttack

Community Member, 12 Posts

16 December 2009 at 7:14am

Edited: 16/12/2009 5:02pm

Hi,

Hoping someone can help me... I need to generate an array of arrays in order to populate a GroupedDropdownField on a form.

I have an TrekPage class that lets users add multiple TrekDates via a DataObjectManager, each with a StartDate and EndDate field. I'd love to be able to write a function that iterates through the available TrekPages and creates an array for each consisting of dates, each of which is the result of a function that determines the range of the TrekDate's StartDate & EndDate (like this http://silverstripe.org/template-questions/show/267739#post267739).

i know i can use things like $this->toArray(); (http://doc.silverstripe.org/doku.php?id=dataobjectset) but haven't had much luck so far. And sorry if the above isn't explained very clearly, I'm new to a lot of this..

Thanks,
jack

Avatar
JackAttack

Community Member, 12 Posts

16 December 2009 at 5:01pm

Edited: 16/12/2009 6:25pm

Ok this is what I'm up to so far

1. creates a form with new GroupedDropdownField
2. function makes an array of arrays for each TrekPage (event page) consisting dates returned by the DateRange function. This array is inserted into the third parameter of the GroupedDropdownField.
3. on BookingPage.ss I have $BookingForm which should display a <select> drop-down with dates organised into <optgroups> for each TrekPage.

BookingPage.php
...

function BookingForm() {
		return new Form($this, 'BookingForm', new FieldSet(
			new GroupedDropdownField(
			 	'trek',
				'Trek/Date',			 	
			 	$treksArray
			),

...

}

        function getTreksArray() {
			$trekPage = DataObject::get('TrekPage');
			$treksArray = array();
			foreach($trekPage as $trek) {
				$trekData = array();
				foreach($trek->TrekDate as $trekDate) {
					$dateRange = DateRange($trekDate);
					$trekData->push($dateRange);
				}
				return $trekData;
			}
			return $treksArray;
		}
	
	function DateRange($date) {
		$start = new Date();
		$start->setValue($date->StartDate);
	
		if (!is_null($this->EndDate)) { // Check if there is an end date
		   $end = new Date();
		   $end->setValue($date->EndDate);
		   return $start->RangeString($end);
		} else {
		   return $start->Long();
		}
	}