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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

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

SOLVED: reverse many_many grouping


Go to End


2 Posts   1397 Views

Avatar
Matty Balaam

Community Member, 74 Posts

10 June 2013 at 6:31am

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.

Avatar
Matty Balaam

Community Member, 74 Posts

11 June 2013 at 5:25am

Edited: 11/06/2013 5:26am

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 %>