Jump to:

3429 Posts in 1057 Topics by 734 members

Data Model Questions

SilverStripe Forums » Data Model Questions » SOLVED: reverse many_many grouping

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

Page: 1
Go to End
Author Topic: 394 Views
  • Matty Balaam
    Avatar
    Community Member
    69 Posts

    SOLVED: reverse many_many grouping Link to this post

    I’m still trying to get to grips with many_many and need a bit of help.

    Say for example I had a $db field called 'Tag' on a DataObject. It is easy to adapt the examples on this page: http://doc.silverstripe.org/framework/en/howto/grouping-dataobjectsets and easily group results by a single tag per Object:

    -----
    Tag 1:
    -----

    Object 1
    Object 3

    -----
    Tag 2:
    -----

    Object 2

    But what I wish to do is sort according to a selection of Tags which have been added using a $many_many and this module https://github.com/chillu/silverstripe-tagfield. So, for example Object 3 may now have both 'Tag 1' and 'Tag 2' so I wish to display like:

    -----
    Tag 1:
    -----

    Object 1
    Object 3

    -----
    Tag 2:
    -----

    Object 2
    Object 3

    To do this, I assume I have to adapt the older code for a GroupedList::create on the page, but obviously the join-table is not a DataObject, so how do I go about approaching this?

    Any help at all is very appreciated, I think I have spent my whole Sunday trying to figure this out.

  • Matty Balaam
    Avatar
    Community Member
    69 Posts

    Re: SOLVED: reverse many_many grouping Link to this post

    I had a bit of time away from this, and then coming back to it I was pleased how easy it was to do this.

    In my pages Controller class I have a function:

       public function getTag() {
          $tag = Tag::get();
          if ($tag) return $tag;
       }

    And then on my page template

          <% if getTag %>
          <% loop getTag %>
             <h3>$Title</h3>
                <ul>
                <% loop MyObject %>
                   <li>$Title</li>
                <% end_loop %>
                </ul>
          <% end_loop %>
          <% end_if %>

    394 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.