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

[SOLVED] Managing has_one Relationship in Admin


Reply

5 Posts   893 Views

Avatar
henrik_

3 May 2013 at 2:13am (Last edited: 3 May 2013 2:14am), Community Member, 5 Posts

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

3 May 2013 at 8:41pm Forum Moderator, 5511 Posts

Checkout https://github.com/simonwelsh/silverstripe-GridFieldRelationHandler

Avatar
henrik_

3 May 2013 at 9:19pm Community Member, 5 Posts

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
simon_w

3 May 2013 at 9:42pm Forum Moderator, 474 Posts

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_

3 May 2013 at 9:45pm Community Member, 5 Posts

Awesome! Thank you very much!