mark_s unfortunatly your solution didnt work for me.
Matze0681 however yours worked like a charm!
I was unsure of where to add your code at first so for the benefit of others, my context is that I have extended Member to create LMM_Member. My LMM_Member and Segment objects have a Many - Many relation. I hadded the ManyManyComplexTableField and onBeforeWrite() in my LMM_Member extension and my LMM_Segment object remained the same. See below for code example:
LMM_Member
class LeadManagementMember extends DataObjectDecorator {
//For some reason with this SS build extraStatics() doesnt build properly, you must build with extraDBfields (which works but throws deprecated warning)
//public function extraDBfields() {
public function extraStatics() {
return array(
'has_many' => array(
'Leads' => 'LMM_Lead'
),
'many_many' => array(
'Segments' => 'LMM_Segment'
)
);
}
public function updateCMSFields(FieldSet &$fields) {
//Only add these fields if the current user is a LMM_User
if(Permission::checkMember($this->owner->ID, "LMM_ACCESS")) {
$table = new ManyManyComplexTableField(
$this->owner,
'Segments',
'LMM_Segment',
array(
'ID' => 'ID',
'DisplayVal' => 'Segment Name'
)
);
$table->showPagination = false;
$table->setParentClass($this->owner->ClassName);
$fields->addFieldToTab('Root.Segments', $table);
}
}
public static $write_count = 0;
function onBeforeWrite(){
parent::onBeforeWrite();
//workaround for saving correct ManyMany Relation in Popup
//$write_count : Make sure only updated once
if(self::$write_count == 0 && isset($_REQUEST['Segments'])){
$segments = $_REQUEST['Segments'];
//remove not needed array key
unset($segments['selected']);
//remove all relations to the DataObject first.(Needed if relations get de-selected in Table)
$this->owner->Segments()->removeAll();
foreach($segments as $segmentKey => $segmentID){
$segments = DataObject::get_by_id('LMM_Segment',(int)$segmentID);
if(isset($segments->ID)){
$this->owner->Segments()->add($segments);
}
}
self::$write_count++;
}
}
}
LMM_Segment
class LMM_Segment extends DataObject {
public static $db = array(
'DataVal' => 'Varchar(255)',
'DisplayVal' => 'Varchar(255)'
);
public static $belongs_many_many = array(
'Members' => 'Member'
);
}
Thanks again Matzeo!