如何在 GridField 摘要中显示来自 many_many 关系的标题?
我用 RelationName.Title 尝试过,但结果只是一个空字段
应该有几个解决方案:
$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
(可能不是最好的示例,但希望您明白这一点,尽管未经测试)。
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
在不同的网格上使用不同的字段