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.

General Questions /

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

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

Image caption


Go to End
Reply


2 Posts   1471 Views

Avatar
Christy

Community Member, 58 Posts

30 January 2010 at 10:11am

Is there any reasonably easy way for the end user to add a caption to an image inserted through the CMS?

Thanks.

Avatar
Juanitou

Community Member, 323 Posts

31 January 2010 at 7:17am

Edited: 31/01/2010 7:19am

Hi!

I’m not sure if it is good practice, I’d prefer to extend Image class instead of this, but I didn’t arrive to. This MyImage class allows for a caption that you can switch on or off in templates with <% if ShowImagesTitle %><p>$Legend</p><% end_if %>:

mysite/code/MyImage.php

<?php
/*
** You haven't been able to extend directly Image and add the boolean field
*/
class MyImage extends DataObject {
	static $db = array (
		'ShowImagesTitle' => 'Boolean',
		'Legend' => 'Text'
	);
	static $has_one = array (
		'Image' => 'Image',
		'Page' => 'Page'
	);
	public function getCMSFields_forPopup()	{
		$myImageField = new ImageField('Image');
		$myImageField->setAllowedExtensions(array('jpg','gif','png'));
		return new FieldSet(
			$myImageField,
			new TextField('Legend'),
			new CheckboxField('ShowImagesTitle', 'Show legend')
		);
	}
}
?>

Then in your Page class, or a more specific one:

mysite/code/Page.php

// Pages can have many images (see MyImage for the other side of the relation)
public static $has_many = array(
	'Images' => 'MyImage'
);

Then later in getCMSFields() you can use, or not, ImageDataObjectManager (included in DOM module):

// This will add a checkbox on the CMS to switch the legend (Title) on images (function later)
// $fields->addFieldToTab('Root.Content.Images', new CheckboxField('ShowImagesTitle', 'Show Title as legend.'));
$fields->addFieldToTab('Root.Content.Images', new ImageDataObjectManager(
	$this,
	'Images',
	'MyImage',
	'Image',
	array(
		'Legend' => 'Legend',
		'ShowImagesTitle' => 'Show'
	),
	'getCMSFields_forPopup'
	)
);

Hope it helps (and that I get corrected with a better way of doing it),
Juan