.Nice formating kills column sorting

ss 3.6

I have added the following code to the page and although it works fine. I want to be able to sort the columns (ascending and descending) PricePerNight and FeaturedOnHomepage, but using .Nice formatting make the column sort feature inactive for some reason. Does anyone know any work arounds to have both.

private static $summary_fields = array (
‘GridThumbnail’ => ‘’,
‘PricePerNight.Nice’ => ‘Price’,
‘Title’ => ‘Title’,
‘Status’ => ‘Status’,
‘Proptype.Title’ => ‘Type’,
‘Pricetype.Title’ => ‘Type’,
‘Bedrooms’ => ‘Beds’,
‘NiceDate.Nice’ => ‘Updated’,
‘countImages’ => ‘Images’,
‘CreatedDate’ => ‘Added’,
‘FeaturedOnHomepage.Nice’ => ‘Featured?’
);

The sorting only works when the field is ‘raw’. Rather than use Nice, maybe you can consider using javascript to modify it?

This is frequently encountered and a bit of a shortcoming in form scaffolding currently. There’s been discussion about improving this though. For now you can try using raw values:

private static $summary_fields = array (
	'PricePerNight' => 'Price',
	'FeaturedOnHomepage' => 'Featured?'
);

Then modifying their formatting directly in the gridfield. Unfortunately this means you need to manually update any corresponding gridfield instances you have explicitly created, as well as any that are automatically generated (scaffolded) for your data model, e.g. in ModelAdmin interfaces.

// Make gridfield values nice to read while preserving sorting
$columns = $config->getComponentByType('GridFieldDataColumns');
$columns->setFieldCasting(array(
	'PricePerNight' => 'Currency->Nice',
	'FeaturedOnHomepage' => 'Boolean->Nice',
));
1 Like

Found this reply when trying to remember for myself how to do this :joy:

Here is an updated example for customising ModelAdmin in SS4:

use SilverStripe\Admin\ModelAdmin;
use SilverStripe\Forms\GridField\GridFieldDataColumns;

class ResourceAdmin extends ModelAdmin
{
    private static $managed_models = [
        'RoomType',
        'RoomAmenity',
    ];

    public function getEditForm($id = null, $fields = null)
    {
        $form = parent::getEditForm($id, $fields);

        // $gridFieldName is generated from the ModelClass, eg if the Class 'Product'
        // is managed by this ModelAdmin, the GridField for it will also be named 'Product'
        $gridFieldName = $this->sanitiseClassName($this->modelClass);

        if (
            $gridFieldName == 'RoomType'
        ) {
            $gridField = $form->Fields()->fieldByName($gridFieldName);
            // Make gridfield values nice to read while preserving sorting
            $columns = $gridField->getConfig()->getComponentByType(GridFieldDataColumns::class);
            $columns->setFieldCasting(array(
                'PricePerNight' => 'Boolean->Nice',
                'FeaturedOnHomepage' => 'Boolean->Nice',
            ));
        }

        return $form;
    }
}
3 Likes