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

Reusable Dropdown arrays


Go to End


3 Posts   2852 Views

Avatar
Chris J

Community Member, 10 Posts

10 November 2010 at 1:22pm

Hi

I would like to store some arrays which I can call from any page type and DataObject.
The arrays are just to populate dropdown elements in the CMS.

Here is some example DataObject code which uses an array inside the DataObject:

class TripDay extends DataObject {
 
	static $db = array(
		'Day' => 'Text',
		'DaySum' => 'Text',
		'DayDesc' => 'Text'
	);
	
	static $has_one = array(
		'TripPages' => 'TripPage'
	);
	
	function getCMSFields_forPopup() {
		
		$f = new FieldSet();
		
		
		$weekdays = array(
			'' => '(Please Select)',
			'Monday' => 'Monday',
			'Tuesday' => 'Tuesday',
			'Wednesday' => 'Wednesday',
			'Thursday' => 'Thursday',
			'Friday' => 'Friday',
			'Saturday' => 'Saturday',
			'Sunday' => 'Sunday'
		);
		
		$f->push( new DropdownField('Day', 'Day of week', $weekdays) );
		$f->push( new TextField( 'DaySum', 'Summary of day' ) );
		$f->push( new TextAreaField('DayDesc', 'Full description', '15' ) );
		
		return $f;
	}
	
}

This works great but I would like to access this array and others from other DataObjects and Page types.

What would be a good way to do that?

Avatar
Willr

Forum Moderator, 5523 Posts

10 November 2010 at 4:12pm

A great way to store that sort of information is using an Enum datafield. For example change your db array to

static $db = array( 
      'Day' => 'Enum("Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday")', 
...
   ); 

This ensures that your data can only take on those values and you can get your day map by using

// $foo will have a map of your enum
$foo = singleton('TripDay')->dbObject('Day')->enumValues();

You would then also define the default 'Please Select' text as the 6th agrument to the DropdownField. http://api.silverstripe.org/2.4/forms/fields-basic/DropdownField.html

Avatar
Chris J

Community Member, 10 Posts

17 November 2010 at 4:29pm

Hey thanks Willr that's great

I didn't know about using

singleton()
like that. So I now have a dataObject which holds all of the dropdown element arrays that I need to reuse, and I can grab them from anywhere. Sweet