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.

Data Model Questions /

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

[SOLVED] Adding/Removing ManyToMany References with ModelAdmin

Go to End

2 Posts   1606 Views


Community Member, 4 Posts

26 February 2011 at 11:01pm

Edited: 26/02/2011 11:54pm

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


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 :)