search
top

Silverstripe 3.0.2 Grid Fields With Thumbnails

Silverstripe 3 has been out for a few months now, and most the big bugs have been fixed… This tutorial describes the code required to set up a grid feild to manage ‘Has Many’ relations. Eg – a staff page that lists many staff members.

Also, we’ll add in some code that will make the table list in the CMS display a wee thumbnail of each staff member – making it much easier for CMS users to manage the content.

silverstripe

Create the Staff Page

Create StaffPage.php

This is the page on your site that contains all the staff page. Eg, one ‘staff page’ -> ‘has many’ -> ‘staff members’

<?php

classStaffPageextendsPage{publicstatic $has_many = array('StaffMembers'=>'StaffMember');publicfunction getCMSFields(){
   		$fields = parent::getCMSFields();
		
		$gridFieldConfig =$gridFieldConfig =GridFieldConfig_RecordEditor::create();
		$gridfield =newGridField("StaffMembers","StaffMember", $this->StaffMembers, $gridFieldConfig);			
		$fields->addFieldToTab('Root.Staff', $gridfield);return $fields;}}classStaffPage_ControllerextendsPage_Controller{}

Create the Staff Member Object

Create StaffMember.php

This is the object that contains data about each staff member. They belong to a Staff Page

 

<?php

  classStaffMemberextendsDataObject{publicstatic $db = array('Name'=>'Varchar','Details'=>'HTMLText');publicstatic $has_one = array('Image'=>'Image','Page'=>'Page');}

 

In the code above, we simple create a DataObject, and define two feilds, a name, and a details.

We also attach the DataObject to an image object (allowing us to add an image) and to a page – this forms the connection with the Staff page it belongs to

At this stage, upload the files, run a dev/build and create a ‘staffPage’ in your CMS. You should be able to see a datagrid and start adding staff members and photos.

Displaying Thumbnails in your Grid Field in the CMS

However, the grid field will probably just list your items by their ID – which is a bit meaningless.

// Summary fields publicstatic $summary_fields = array('Thumbnail'=>'Thumbnail','Name'=>'Name');publicfunction getThumbnail(){return $this->Image()->CMSThumbnail();}

By adding the code above into the StaffMember.php file,  we can define the fields (summary_fields) that are shown on the summary table in the CMS.

The function getThumbnail takes the attached Image, and creates a thumbnail to use in the summary fields.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

top