Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

3.1.12 ImageDecorator -> get owner relationName


Go to End


3 Posts   1015 Views

Avatar
timo

Community Member, 47 Posts

4 June 2015 at 10:39am

Edited: 04/06/2015 10:46am

i have a class: "class ImageBlock extends Block".
this ImageBlock has_one Image.
Image is decorated: Object::add_extension('Image', 'MyImageDecorator');
In MyImageDecorator : function onAfterWrite() { if ( ?????? $this->owner-> ?????? here i need to get 'ImageBlock' }
thanks.timo

Avatar
Devlin

Community Member, 344 Posts

4 June 2015 at 7:50pm

You need to create a relation back to the ImageBlock. Something like:

class ImageBlock extends Block {
	private static $db = array(
		'Title' => 'Varchar(128)',
	);
	private static $has_one = array(
		'Image' => 'Image',
	);
}

class ImageExtension extends DataExtension {
	private static $belongs_to = array(
		'ImageBlock' => 'ImageBlock.Image', // reverse $has_one
	);
	public function onAfterWrite() {
		$imgObj = $this->owner; // image object

		echo $imgObj->Title; // image title
		echo $imgObj->ImageBlock()->Title; // imageblock title
	}
}

http://docs.silverstripe.org/en/developer_guides/model/relations/#belongs-to

Avatar
Devlin

Community Member, 344 Posts

4 June 2015 at 11:42pm

Though, maybe an Image can appear in multiple ImageBlocks, so it could be better to go with $has_many instead.

class ImageExtension extends DataExtension {
	private static $has_many = array(
		'ImageBlocks' => 'ImageBlock',
	);
	public function onAfterWrite() {
		$imgObj = $this->owner; // image object

		echo $imgObj->Title; // image title
		foreach($imgObj->ImageBlocks() as $block) {
			echo $block->Title; // imageblock title
		}
	}
}