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.

Customising the CMS /

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

[SOLVED] Managing has_one Relationship in Admin


Go to End
Reply


5 Posts   1688 Views

Avatar
henrik_

Community Member, 5 Posts

3 May 2013 at 2:13am

Edited: 03/05/2013 2:14am

Hey there,
I'm new to Silverstripe.

I want to show a Custom-Header on every Page, so I created a DataObject called Header.

class Header extends DataObject{
	const BUTTONS = "Enum('NONE, DONATE, BECOME_MEMBER', 'NONE')";
	static $db = array(
		'Title' => 'Varchar(255)',
		'GeneralDescription' => 'Text',
		'BigButton' => self::BUTTONS,
		'SmallButton' => self::BUTTONS
	);
	static $has_one = array(
		'BackgroundImage' => 'Image',
	);
	static $has_many = array(
		'Pages' => 'Page'
	);	
}

Every Page now should have a connection to a header. It should be possible to choose either a existing Header-Entry or create a new one (simple drowdown isn't enough). This is how Page.php looks like:

class Page extends SiteTree {

	public static $db = array(
	);

	public static $has_one = array(
		'Header' => 'Header'
	);
	
	public function getCMSFields(){
		$fields = parent::getCMSFields();
		//what to add here?	
		return $fields;
	}
}

Can I use a GridField here? This would be the functionality I want to have. The problem is, that GridFields only work for Lists and not for single Models?

Thanks!

Avatar
Willr

Forum Moderator, 5521 Posts

3 May 2013 at 8:41pm

Avatar
henrik_

Community Member, 5 Posts

3 May 2013 at 9:19pm

Thank you!
But this just lets me choose existing header, doesn't it?
More often the user will create a new header. Any idea how I can achieve this?

Avatar
(deleted)

Community Member, 473 Posts

3 May 2013 at 9:42pm

If you add a GridFieldAddNewButton component to the GridFieldConfig then you'll also be able to create new records. Alternatively, you could start with a config that already includes it. For example:

	public function getCMSFields() {
		$fields = parent::getCMSFields();
		$gf = GridFieldConfig_RecordEditor::create();
		$gf->addComponent(new GridFieldHasOneRelationHandler($this, 'Header'), 'GridFieldPaginator');
		$field = new GridField('Header', null, Header::get(), $gf);
		$fields->addFieldToTab('Root.Main', $field, 'Content');
		return $fields;
	}

will let you manage the has_one relation as well as viewing, editing, adding and deleting Headers.

Avatar
henrik_

Community Member, 5 Posts

3 May 2013 at 9:45pm

Awesome! Thank you very much!