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.

DataObjectManager Module /

Discuss the DataObjectManager module, and the related ImageGallery module.

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

$has_one / $has_many DataObject to DataObject


Go to End


2 Posts   1815 Views

Avatar
Garrett

Community Member, 245 Posts

11 April 2012 at 1:26am

Hi,

I am used to creating a $has_many -> $has_one relationship from a Page to a DataObject, however that's not what I want this time and I am having trouble getting the Parent ID to save into the Child table. Here is the parent object:

[pre]

class Service extends DataObject { 
	
	....
	
	static $has_one = array(
		"ServiceHolder" => "ServiceHolder"		
	);

	static $has_many = array(
		"SubServices" => "SubService"
   	);

	....

	function getCMSFields_forPopup() {

		$fields = new FieldSet();
		
		$fields->push(new TextField("ServiceName", "Name of Service"));
		$fields->push(new SimpleTinyMCEField("ServiceDescription", "Description"));

		return $fields;

	}
	
}

[/pre]

And here is my child object:

[pre]

class SubService extends DataObject { 
	
	....
	
	static $has_one = array(
		"Service" => "Service"		
	);

	....

	function getCMSFields_forPopup() {

		$fields = new FieldSet();
		
		$fields->push(new TextField("SubServiceName", "Name of Service"));
		$fields->push(new SimpleTinyMCEField("SubServiceDescription", "Description"));
		
		$services = DataObject::get("Service");
		$services_dropdown = new DropdownField("Service", "Parent Service", $services->toDropDownMap("ServiceID","ServiceName"));
		$fields->push($services_dropdown);

		return $fields;

	}
	
}

[/pre]

What I am trying to do here is to allow the user to choose which Service each SubService belongs to. When you create/edit a SubService, I want to be able to choose the Parent Service from a dropdown list. However the result of this code is such that I see a dropdown which contains only one Service -- the first one -- that which has an ID of 0.

Firstly, why will my dropdown not show all the Services? What am I doing wrong? How do I save the value of the selected Parent into the child object?

Thank you in advance,
Garrett

Avatar
Willr

Forum Moderator, 5523 Posts

11 April 2012 at 7:03pm

$services_dropdown = new DropdownField("Service", "Parent Service", $services->toDropDownMap("ServiceID","ServiceName"));

That 'Service' $name parameter has to be ServiceID

$services_dropdown = new DropdownField("ServiceID", "Parent Service", $services->map());