Jump to:

3373 Posts in 998 Topics by 712 members

Data Model Questions

SilverStripe Forums » Data Model Questions » [SOLVED] Adding/Removing ManyToMany References with ModelAdmin

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

Page: 1
Go to End
Author Topic: 1051 Views
  • bcc2k
    Avatar
    Community Member
    4 Posts

    [SOLVED] Adding/Removing ManyToMany References with ModelAdmin Link to this post

    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

  • bcc2k
    Avatar
    Community Member
    4 Posts

    Re: [SOLVED] Adding/Removing ManyToMany References with ModelAdmin Link to this post

    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

    1051 Views
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.