How to display many_machines in a page template in Silverstripe

Our site has an object called "TrailNotice", which has many_many relation to the page type "TrailSection".

class TrailNotice extends DataObject { private static $many_many = array( 'TrailSections' => 'TrailSection' ); 

This allows you to use one TrailNotice through several TrailSections through the flags in the CMS:

 $fields->addFieldToTab('Root.Main', new CheckboxSetField('TrailSections', 'Applies to which trail sections?', DataObject::get('TrailSection')->map('ID', 'Title'))); 

How to display TrailNotices attached to a TrailSection in a TrailSection page controller?

I started with the following code:

 class TrailSection_Controller extends Page_Controller { public function TrailNotices(){ $TrailNotices = DataObject::get('TrailNotice'); return $TrailNotices; } 

But this will get all TrailNotice objects. How do I filter them, so only TrailNotices attached to the TrailSection are displayed?

+5
source share
3 answers

You need to define many_many in both directions, then you can access it from both sides. One side has $many_many

 class TrailNotice extends DataObject { private static $many_many = array( 'TrailSections' => 'TrailSection' ); 

on the other hand you need to define $belongs_many_many

 class TrailSection extends DataObject { private static $belongs_many_many = array( 'TrailNotices' => 'TrailNotice' ); 

Then in your template, you can simply call up the list of relations and iterate over it:

 <% loop $TrailNotices %> $Title <% end_loop %> 

Cm. infographic for all possible relationships (thanks to @nightjar for providing graphics).

+6
source

You should implement $ belongs_many_many in your TrailSection model, something like this:

 class TrailSection extends DataObject { private static $belongs_many_many = array( 'TrailNotices' => 'TrailNotice' ); } 

Then you can simply iterate over $ TrailNotices into the TrailSection.ss template without doing anything in your controller:

 <% loop $TrailNotices %> $Title<br> <% end_loop %> 

You can check out the sample mentor at Stephen's Relationship Management Dataobject link.

+3
source

SilverStripe stores the multi-valued RelationList relationships that can be accessed by the object using $this->RelationName() (in this case $this->data()->TrailNotices() ). RelationList is a subclass of DataList , so you can treat it the same way as DataObject::get() to filter a list.

 class TrailSection_Controller extends Page_Controller { public function TrailNotices(){ $TrailNotices = $this->data()->TrailNotices(); return $TrailNotices; } 

For more information about SilverStripe ORM and DataObject Relations, see the " Data Relationship Management" help topic and (newer content) SilverStripe Tutorials

0
source

All Articles