Tag: thumbnails

  • Silverstripe 3.0 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 field 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.

    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’

    class StaffPage extends Page
    {
        public static $has_many = ['StaffMembers' => 'StaffMember'];
    
        public function getCMSFields()
        {
            $fields = parent::getCMSFields();
    
            $gridFieldConfig = GridFieldConfig_RecordEditor::create();
            $gridfield = new GridField("StaffMembers", "StaffMember", $this->StaffMembers, $gridFieldConfig);
            $fields->addFieldToTab('Root.Staff', $gridfield);
            return $fields;
        }
    }
    
    class StaffPage_Controller extends Page_Controller
    {
    }

    Create the Staff Member Object

    Create StaffMember.php

    class StaffMember extends DataObject
    {
        public static $db = ['Name' => 'Varchar', 'Details' => 'HTMLText'];
        public static $has_one = [
            'Image' => 'Image',
            'Page'  => 'Page',
        ];
    }

    This is the object that contains data about each staff member. They belong to a Staff 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

    // Summary fields
    public static $summary_fields = ['Thumbnail' => 'Thumbnail', 'Name' => 'Name'];
    
    public function getThumbnail()
    {
        return $this->Image()->CMSThumbnail();
    }

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

    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.