I have 3 classes: BlogHolder, BlogEntry, and BlogCategory. BlogHolder is a parent of BlogEntries. I have a many_many relation on BlogEntry for BlogCategory (and BlogCategory has a belongs_many_many to BlogEntry).
The problem is I also want to associate a BlogCategory to the specific BlogHolder so each BlogHolder can have a separate set of categories. I'm having trouble passing the BlogEntry to the popup for the BlogCategory so I can save $blogentry->Parent() to a has_one field on BlogCategory.
Sorry, this is kind of confusing so I'll post some code. The way I'm doing it right now works but seems pretty sketchy. It's probably just late and my brain isn't working...
class BlogHolder extends Page {
static $allowed_children = array(
'BlogEntry'
);
//...
}
class BlogEntry extends Page {
static $many_many = array(
'BlogCategories' => 'BlogCategory',
);
public function getCMSFields() {
$fields = parent::getCMSFields();
$categories = new ManyManyDataObjectManager(
$this,
'BlogCategories',
'BlogCategory',
array(
'Name' => 'Name',
),
'getCMSFields_forPopup'
);
$fields->addFieldToTab("Root.Content.Main", $categories);
//...
}
class BlogCategory extends DataObject {
static $db = array(
'Name' => 'Varchar(255)',
'URLSegment' => 'Varchar(255)'
);
static $has_one = array(
'BlogHolder' => 'BlogHolder',
);
static $belongs_many_many = array(
'BlogEntries' => 'BlogEntry',
);
public function getCMSFields_forPopup() {
return new FieldSet(
new TextField('Name')
);
}
protected function onBeforeWrite() {
if (isset($this->record['ctf[sourceID]'])) {
$entryID = $this->record['ctf[sourceID]'];
$this->BlogHolderID = DataObject::get_by_id('BlogEntry', $entryID)->Parent()->ID;
}
$this->URLSegment = singleton('Page')->generateURLSegment($this->Name);
parent::onBeforeWrite();
}
public function CategorySegment() {
return 'category/' . $this->URLSegment;
}
}