2

I am trying to output a set of icons (coming from a set of GuidePages), where I always want to show the 5 icons, but need to be able to select which ones apply to this particular page.

enter image description here

In the pages where I want to display them I am doing:

private static $many_many = array(
        'GuidePages' => GuidePage::class
    );

and

$source = GuidePages::get()->map('ID', 'Name');
$fields->addFieldToTab('Root.Main',CheckboxSetField::create('GuidePages','Select guide which apply', $source));

Which is fine and I can select the icons, but it will obviously only output the actual icons I have selected (ie 3 instead of all 5).

I am trying to find a way of always showing the 5, but being able to select the few that apply and loop all of them in the template (adding an active class to the selected ones).

It doesn't necessarily need to be a many_many or any relationship between the 2 sets of pages, if there is another easier way to do it...ie just putting the values into a DataList or something...

scrowler
  • 24,273
  • 9
  • 60
  • 92
galilee
  • 449
  • 3
  • 12
  • You may consider using a "many many extra field" to identify whether it's selected, then you can still iterate your GuidePages list and have that field available to check: https://docs.silverstripe.org/en/4/developer_guides/model/relations/#automatic-many-many-table – scrowler Apr 28 '19 at 21:23
  • Thanks for the suggestion Robbie, ended up with a slightly different approach.. – galilee May 01 '19 at 20:59

1 Answers1

2

Ended up going with:

public function getCMSFields()
{
    $fields = parent::getCMSFields();
    $source = GuidePage::get()->map('ID', 'Name');        
    $fields->addFieldToTab('Root.Main', CheckboxSetField::create('GuidePages', 'Select guides which apply', $source));
    return $fields;
}

public function getAllGuidePages()
{
  $out = [];
  $source   = GuidePage::get();
  $selected = $this->GuidePages()->getIDList();
  foreach ($source as $page) {
    $out[] = [
        'Class' => (in_array($page->ID, $selected)) ? 'active' : '',
        'Name'  => $page->Name(),
        'Icon'  => $page->PageIcon()->Link(),
    ];
  }
  return ArrayList::create($out);
}

and in template

<% loop getAllGuidePages %>
    <div class="$Class">
        <img src="$Icon">
        $Name
    </div>
<% end_loop %>
galilee
  • 449
  • 3
  • 12