在GridField中显示来自many_many关系的标题 - Silverstripe

时间:2013-10-22 16:59:08

标签: silverstripe

如何在GridField摘要中显示many_many关系的标题?

我用RelationName.Title尝试了它,但结果只是一个空字段

2 个答案:

答案 0 :(得分:2)

应该有几个解决方案:

在链接的DataObject上定义$summary_fields

private static $summary_fields = array(
    'YourFieldName',
    'AnotherField'
);

或定义关系的Page / DataObject上的GridFieldConfig

$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(      
    'FieldName' => 'GridFieldColumnName',
    'AnotherFieldName' => 'AnotherGridFieldColumnName',
));

$configGridFieldConfig使用的GridField个实例。

修改

要对GridField中包含的数据进行更高级的格式化/控制,您可以使用setFieldFormatting

$config->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(      
    'TeamLink' => 'Edit teams'
));

$config->getComponentByType('GridFieldDataColumns')->setFieldFormatting(array(
    'TeamLink' => function($value, $item)
    {
      // $item here would be a TeamMember instance
      // since the GridField displays TeamMembers

      $links = 'No teams';

      $teamModelAdminClass = 'TeamModelAdmin'; //change to your classname
      $teams = $item->Teams(); // get the teams

      if ( $teams->count() > 0 )
      {
        $links = '';
        $teamClass = $teams->dataClass;

          $teamAdminURL = Config::inst()->get($teamModelAdminClass, 'url_segment');
          $teamEditAdminURL = 'admin/'.$teamAdminURL.'/'.$teamClass.'/EditForm/field/'.$teamClass.'/item/';       

          foreach($teams as $team)
          {
            $links .= '<a href="'.$teamEditAdminURL.$team->ID.'/edit">Edit '.$team->Title.'</a><br/>';
          }
      }

      return $links;
    }
));

此处setFieldFormatting将输出编辑链接,指向TeamMember属于TeamLink定义的setDisplayFields列的所有团队(可能不是最佳示例,但希望您获得想法,虽然未经测试)。

答案 1 :(得分:1)

colymba 的答案已经说明了大部分内容,但此外您还可以在$summary_fields中指定方法。这允许您在GridField中或在需要时显示图像缩略图,将您自己的字符串与many_many关系的标题拼凑在一起。

class TeamMember extends DataObject {
    private static $db = array(
        'Title' => 'Text',
        'Birthday' => 'Date',
    );
    private static $has_one = array(
        'Photo' => 'Image'
    );
    private static $has_many = array(
        'Teams' => 'Team'
    );
    private static $summary_fields = array(
        'PhotoThumbnail',
        'Title',
        'Birthday',
        'TeamsAsString',
    );
    public function getPhotoThumbnail() {
        // display a thumbnail of the Image from the has_one relation
        return $this->Photo() ? $this->Photo()->CroppedImage(50,50) : '';
    }
    public function getTeamsAsString() {
        if (!$this->Teams()) {
           return 'not in any Team'; 
        }
        return implode(', ', $this->Teams()->Column('Title'));
        // or if one field is not enough for you, you can use a foreach loop:
        // $teamsArray= array();
        // foreach ($this->Teams() as $team) {
        //     $teamsArray[] = "{$team->ID} {$team->Title}";
        // }
        // return implode(', ', $teamsArray);
    }
}
colymba 指出的那样,您可以使用setDisplayFields在不同的网格上使用不同的字段