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.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Create belongs_many_many relation on self


Go to End
Reply


1124 Views

Avatar
MarijnKampf

Community Member, 174 Posts

29 July 2010 at 3:31am

I've been trying to create a $many_many / $belongs_many_many relation with self. I've come across several use cases for this, e.g. setting groups of related pages so I can add 'See also links' to pages, Properties that can be booked together etc.

I've gotten a has_many relation to work on self, but I would like the relation to be maintained on both ends. That is, if I set the checkbox on Page A that it is related to Page B, the checkbox for Page A should be automatically set for Page B (Just as it would work with other $belongs_many_many relations).

I've tried the code below (based on tutorial 5) where I want to set which modules are related (e.g. i18n and Translatable). My code only maintains the relation in one direction, the other side isn't maintained.

Is there a way of achieving a bi-directional relation?

<?php

class Module extends Page {

	static $db = array(
		'Name' => 'Text'
	);

	static $many_many = array(
		'RelatedModules' => __CLASS__
	);

	static $belongs_many_many = array(
		'Projects' => 'Project',
		'Modules' => __CLASS__
	);

	function getCMSFields() {
		$fields = parent::getCMSFields();

		$fields->addFieldToTab( 'Root.Content.Main', new TextField( 'Title', 'Title' ) );

		$tablefield = new ManyManyComplexTableField(
			$this,
			'RelatedModules',
			'Module',
			array(
				'Title' => 'Title',
			),
			'getCMSFields_forPopup'
		);
		$tablefield->setAddTitle( 'A Module' );

		$fields->addFieldToTab( 'Root.Content.RelatedModules', $tablefield );

		return $fields;
	}

	function getCMSFields_forPopup() {
		$fields = new FieldSet();
		$fields->push( new TextField( 'Name' ) );
		$fields->push( new ManyManyComplexTableField($this, 'RelatedModules', "Module", array('Title' => 'Title')));
		return $fields;
	}
}

?>