如何在GridField摘要中显示many_many关系的标题?
我用RelationName.Title尝试了它,但结果只是一个空字段
答案 0 :(得分:2)
应该有几个解决方案:
在链接的DataObject上定义$summary_fields
:
private static $summary_fields = array(
'YourFieldName',
'AnotherField'
);
或定义关系的Page / DataObject上的GridFieldConfig
:
$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
列的所有团队(可能不是最佳示例,但希望您获得想法,虽然未经测试)。
答案 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
在不同的网格上使用不同的字段