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

[SOLVED] Adding/Removing ManyToMany References with ModelAdmin


Go to End


2 Posts   1994 Views

Avatar
bcc2k

Community Member, 4 Posts

26 February 2011 at 11:01pm

Edited: 26/02/2011 11:54pm

Hi!
I'm wondering if there's a way to add and remove references to other DataObjects in ModelAdmin without creating/deleting the DataObject.

Imagine the following scenario:
I have Students and a many to many relation with Exams. So students are connected to several Exams which are connected to several Students. A typical bidirectional Many-To-Many relationship.
I want to use ModelAdmin to manage these relationships.
But as it is a Many-To-Many relationship ModelAdmin shows me a "Exams" tab when I go on the Students ModelAdmin-page.
(If it were a one-to-many relationship the Exams would be referenced with a select-box, which allows me to add or remove a reference to an Exam.)
On the Exams-tab on the other hand, I can just create and delete (not add and remove) whole Exams DataObjects. So therefore I can't really manage my many-to-many relationship as I can't add multiple references of the same Exam to different Students.
For example when I delete an Exam of a Student because it doesn't belong to him, then the Exam will be completely deleted (for all students).

As I'm quite new to Silverstripe I'm just wondering if there's another way to manage those many-to-many relationships.

best regards
Andreas

Avatar
bcc2k

Community Member, 4 Posts

27 February 2011 at 2:49am

Edited: 27/02/2011 2:50am

Well I found a solution for my problem.
I had to replace the ComplexTableField that ModelAdmin automatically generates with a ManyManyComplexTableField.

I overwrote the getCMSFields function with the following:

	public function getCMSFields() {
		$fields = parent::getCMSFields();
		$examsField = new ManyManyComplexTableField(
			$this,'Exams', 'Exam');
		$fields->replaceField('Exams', $examsField);
			
		return $fields;
	}

Unfortunately I just read the SS book but not the online tutorials. Well, in Tutorial 5 is a great description of solving this problem :)
http://doc.silverstripe.org/sapphire/en/tutorials/5-dataobject-relationship-management