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, simon_w

Create belongs_many_many relation on self




29 July 2010 at 3:31am Community Member, 164 Posts

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 [url=]has_many relation to work[/url] 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?


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(
            'Title' => 'Title',
      $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;