Search code examples
silverstripesilverstripe-4

How to sort images as part of a many_many in silverstripe?


I have created a $many_many array for $slideImages on my home page. After much reading and trying I am still unable to tell the CMS the order I want the images to appear in the template. By default they are sorted by upload date I believe.

I can create the gridfield but I can't seem to get a textfield to enter in a sorting number. Right now I just finished a rabbit trail that led me to gridFieldComponent but I get an error and the docs are not helping me.

use SilverStripe\Assets\Image;
use SilverStripe\AssetAdmin\Forms\UploadField;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\GridField\GridFieldComponent;
use SilverStripe\Forms\GridField\GridFieldConfig_RelationEditor;
use SilverStripe\Forms\GridField\GridField;

class HomePage extends Page
{
    private static $db = [];

    private static $has_one = [];

    private static $many_many = [
        'SliderImage'=>Image::Class
    ];

    private static $owns = [
        'SliderImage'
    ];
    private static $many_many_extraFields= [
        'SliderImage'=>array(            
            'Sort'=>'Int'
        )         
    ];

    public function getCMSFields(){
        $fields = parent::getCMSFields();

        $fields->addFieldToTab('Root.Attachments', UploadField::create('SliderImage', 'Sllider Images')->setFolderName('HomePageSlides'));

        $gridFieldConfig = GridFieldConfig_RelationEditor::create()->addComponents(

            new GridFieldComponent(TextField('Sort'))
    );

        $gridField = new GridField("SliderImage", "Slider Image", $this->SliderImage()->sort('Sort'), $gridFieldConfig);

        $fields->addFieldToTab("Root.Attachments", $gridField);

        return $fields;
    }
}

The Error I get is:

"Uncaught Error: Cannot instantiate interface SilverStripe\Forms\GridField\GridFieldComponent"


Solution

  • As per wmk's comment, your are missing a new or ::create on the TextField initialization for your Sort field.

    Should be:

    new GridFieldComponent(new TextField('Sort'))
    

    Or better yet:

    GridFieldComponent::create(TextField::create('Sort'))