Jump to:

23453 Posts in 18902 Topics by 2877 members

General Questions

SilverStripe Forums » General Questions » Create belongs_many_many relation on self

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

Page: 1
Go to End
Author Topic: 908 Views
  • MarijnKampf
    Community Member
    164 Posts

    Create belongs_many_many relation on self Link to this post

    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?


    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;


Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.