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   210 Views

Avatar
geekdenz

11 July 2014 at 5:50pm (Last edited: 11 July 2014 5:54pm), Community Member, 34 Posts

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

11 July 2014 at 7:19pm Forum Moderator, 474 Posts

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

11 July 2014 at 7:53pm Community Member, 34 Posts

Thanks for the quick reply! Will try it out.