if you want 1 Player (TeamMember) to be in multiple Teams, and Teams to have multiple Players, you need a many_many. If you use has_many here, then the Team would have a PlayerID, which means there can only be 1 Player in each team.
class TeamPage extends Page {
private static $many_many = array('TeamMembers' => 'TeamMember');
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root', Tab::create('MembersTab', 'Team Members'));
$fields->addFieldToTab('Root.MembersTab', GridField::create('TeamMembers', 'The Team Members', $this->TeamMembers(), GridFieldConfig_RelationEditor::create());
return $fields;
}
}
class TeamMember extends DataObject {
private static $belongs_many_many = array('Teams' => 'TeamPage');
public function getCMSFields() {
$fields = FieldList::create();
if (!$this->isInDB()) {
// if the TeamMember has not been saved yet, display a message that it needs to be saved before teams can be assigned
$fields->push(ReadOnlyField::create('Teams', '', 'Save to assign Teams'));
} else {
$config = GridFieldConfig_RelationEditor::create();
// if you don't want the "add a new team" button on this grid, you can remove that with the following line:
// $config->removeComponentsByType('GridFieldAddNewButton');
$fields->push(GridField::create('Teams', 'Team this Member is in', $this->Teams(), $config);
}
return $fields;
}
}
NOTE here that I used GridFieldConfig_RelationEditor instead of GridFieldConfig_RecordEditor which adds a GridFieldAddExistingAutocompleter to your gridfield that lets you link objects.
TeamPagewould have ahas_manyrelationship toTeamMemberandTeamMemberwould have ahas_onerelationship toTeamPage. If a team member can have multiple teams, and a team can have multiple team members, then you want amany_manyrelationship between to the two. SoTeamPagewould have amany_manylink toTeamMemberandTeamMemberwould have abelongs_many_manylink back toTeamPage- 3dgoo