26/01/2013 5:24am

PHP | Working Example - get ParentID and parentClassname fields on WidgetArea


/*

This example will set ParentID and parentClassName on WidgetArea on any subclass of class Page .
check http://www.silverstripe.org/general-questions/show/22005#post319209 for more info .
*/
//Page.php
static $has_one = array(
//other fields here ....
'Column1' => 'WidgetArea',
'Column2' => 'WidgetArea',
'Column3' => 'WidgetArea',
'Column4' => 'WidgetArea'
);
function onAfterWrite() {
parent::onAfterWrite();
$this->fixWidgetArea();
}

/**
* Return all has_one RelationName(s) to $ClassName as a $k => $v array .
* @param type $ClassName
* @return type
*/
public function getHasOneReltionsToClass($ClassName) {
$merged_arrays = array();

$ancestry = Classinfo:: ancestry($this);
$ancestry_has_one = array();
foreach ($ancestry as $key => $value) {
if (property_exists($value, 'has_one'))
if ($value::$has_one != null) {
$ancestry_has_one[] = $value::$has_one;
}
}
foreach ($ancestry_has_one as $value) {
foreach ($value as $k => $v) {
if ($v == $ClassName) {

$merged_arrays[$k] = $v;
}
}
}
return $merged_arrays;
}

public function fixWidgetArea() {
foreach ($this->getHasOneReltionsToClass('WidgetArea') as $RelationName => $ClassName) {
$RelationNameID = $RelationName . 'ID';
$Object = DataObject::get('WidgetArea')->filter(array('ID' => $this->$RelationNameID))->first();
if ($Object) {
$Object->ParentID = $this->ID;
$Object->ParentClassName = $this->ClassName;
$Object->write();
}
}
}

// ExtendWidgetArea.php
<?php
class ExtendWidgetArea extends DataExtension {

static $db = array(
'ParentID' => 'Int',
'ParentClassName' => 'Text'
);
}
//_config.php
Object::add_extension('WidgetArea', 'ExtendWidgetArea');


Post Comment