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.

Data Model Questions /

DataObject and SiteTree or Page and custom CMS fields


Reply


3 Posts   318 Views

Avatar
geekdenz

Community Member, 34 Posts

11 July 2014 at 5:50pm

Edited: 11/07/2014 5:54pm

Hi,

Code can also be viewed on pastebin: http://pastebin.com/9hvgigkV

I would like to know how to best go about adding a relatively simple has_one relationship. I have a class extending DataObject, lets call it EditedAuthor. It has 2 simple Text data fields.
So, the code looks like this (at the moment):

<?php
class EditedAuthor extends DataObject {

public static $db = array(
'AuthorTitle' => 'Text',
'AuthorCaption' => 'Text',
);
//...
public function getCMSFields() {
$fields = new FieldGroup();
$fields->push(TextareaField::create('AuthorTitle', 'Author title', $this->AuthorTitle));
$fields->push(TextareaField::create('AuthorCaption', 'Author caption', $this->AuthorCaption));
return $fields;
}
}
?>

I have a custom Page Type extending SiteTree (actually our custom Page which extends SiteTree).

In that I have a has_one relationship to EditedAuthor:

<?php
class InformationPage extends Page {

// ...
static $has_one = array(
'Contributors' => 'EditedAuthor',
);
// ...
public function getCMSFields() {
// ...
if (Permission::check('ADMIN')) {
$authorsEditField = singleton('EditedAuthor')->getCMSFields();
$fields->addFieldsToTab('Root.Main', $authorsEditField);
}
}
// ...
}
?>

I couldn't find in the docs how to best do this. The requirement is that I have a DataObject that is not a page type but can be added to a page type because I may want to re-use it later.
Also, this EditedAuthor should be editable only by admins and then save to the DB.
What is the way to do this?

Avatar
simon_w

Forum Moderator, 474 Posts

11 July 2014 at 7:19pm

Have a look at the [hasoneedit](http://addons.silverstripe.org/add-ons/simonwelsh/hasoneedit) module, which allows you to add fields to a form and then have those save into the related has_one. It even creates the object if needed.

Avatar
geekdenz

Community Member, 34 Posts

11 July 2014 at 7:53pm

Thanks for the quick reply! Will try it out.