0

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

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

4

2 回答 2

2

应该有几个解决方案:

$summary_fields在链接的 DataObject 上定义:

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

或在GridFieldConfig定义关系的 Page/DataObject 上使用:

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

$config是您GridFieldConfig使用的实例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(可能不是最好的示例,但希望您明白这一点,尽管未经测试)。

于 2013-10-22T18:29:15.507 回答
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);
    }
}

正如科林巴指出的那样,您也可以setDisplayFields在不同的网格上使用不同的字段

于 2013-10-22T23:10:23.130 回答