Silverstripe-循环来自many_many关系的所有项目

问题描述 投票:2回答:1

我正在尝试输出一组图标(来自一组GuidePages),我总是想要显示5个图标,但需要能够选择适用于此特定页面的图标。

enter image description here

在我想要显示它们的页面中,我正在做:

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

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

这很好,我可以选择图标,但显然只会输出我选择的实际图标(即3而不是全部5)。

我试图找到一种总是显示5的方法,但能够选择少数应用并在模板中循环所有这些(将活动类添加到选定的类)。

它不一定需要是两组页面之间的多个或任何关系,如果有另一种更简单的方法来做到这一点......即只是将值放入DataList或其他东西......

php silverstripe silverstripe-4
1个回答
2
投票

结束:

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);
}

并在模板中

<% loop getAllGuidePages %>
    <div class="$Class">
        <img src="$Icon">
        $Name
    </div>
<% end_loop %>
© www.soinside.com 2019 - 2024. All rights reserved.