26/08/2011 5:57pm

PHP | Problem - Silverstripe Content Block manager


// This all requires DataObjectManager

http://www.silverstripe.org/dataobjectmanager-module/

_config.php

<?php

Object::add_extension('Page', 'BlockExtension');
SortableDataObject::add_sortable_class('Block');

code/Block_DataObject.php

<?php

class Block extends DataObject
{
static $db = array(
'Title' => 'VarChar',
'Content' => 'HTMLText',
);

static $belongs_many_many = array(
'Pages' => 'Page',
);
}

code/BlockExtension_Extension.php

<?php

class BlockExtension extends DataObjectDecorator
{
public function extraStatics() {
return array(
'many_many' => array(
'Blocks' => 'Block',
)
);
}

public function updateCMSFields(FieldSet $fields)
{
$fields->addFieldToTab('Root.Content.Blocks', new ManyManyDataObjectManager(
$this->owner,
'Blocks',
'Block'
));
}
}

In any template that extends Page.. just add

<% if Blocks %>
<div id="blocks">
<% control Blocks %>
<div class="block">$Title<br>$Content</div>
<% end_control %>
</div>
<% end_if %>

Or thereabouts.. The HTML is up to you :)


1 Comments 1 Solutions

26/08/2011 6:18pm

PHP | Solution - HRabbit

Additional functions to allow getting a block by ID or by title

Template


<% control getBlock(test) %>
$Title
$Content

<% end_control %>


Replace test with a valid title or a block ID

Add this function to the code/BlockExtension_Extension.php

public function getBlock($id = null)
{
if(!empty($id))
{
if(preg_match('/\d+/', $id))
return DataObject::get_by_id('Block', (int)$id);
else
return DataObject::get_one('Block', "Title = '{$id}'");
}
return array();
}

Post Comment