Sorting numbers seems broken

I have this simple field in a mixin element:

fields:
    rank:
        label: Rank
        type: number

But when I look at the list and have it descendingly sorting by Rank then 10 is the last entry. When I switch it down to 9 it becomes the top entry. The same happens when I use the sort by rank in a collection component.
image

I tried adding sortable: true but it didn’t help and I am not yet sure if this would be required or not.

Hi,

it is for the reason that the tailor stores the input number as a text, not an integer.

I suspected that but this is not really ideal. Especially if there is no alternative(?). What field types are sortable? Ok I can use the alphabet but, no… A date also is just a hack.

You can create your own field, if you absolutely need it now

this override number to correct format in DB:

<?php namespace PluginAuthor\PluginName\ContentFields;

use Tailor\Classes\ContentFieldBase;
use October\Contracts\Element\FormElement;
use October\Contracts\Element\ListElement;
use October\Contracts\Element\FilterElement;

class Number extends ContentFieldBase
{
    public function defineConfig(array $config) {}

    public function defineFormField(FormElement $form, $context = null) 
    {
        $form->addFormField($this->fieldName, $this->label)->useConfig($this->config);
    }

    public function defineListColumn(ListElement $list, $context = null) 
    {
        $list->defineColumn($this->fieldName, $this->label)->displayAs('number');
    }

    public function defineFilterScope(FilterElement $filter, $context = null) 
    {
        $filter->defineScope($this->fieldName, $this->label)->displayAs('number');
    }

    public function extendModelObject($model) {}

    public function extendDatabaseTable($table)
    {
        $table->integer($this->fieldName)->nullable();
    }
}

then in Plugin.php

public function registerContentFields()
    {
        return [
            \PluginAuthor\PLuginName\ContentFields\Number::class => 'number'
        ];
    }

and don’t forget afterwards SAVE and MIGRATE your tailor blueprint

2 Likes

Thanks @mcore. We’ve added this for the upcoming 3.4 release. We still need to consider how to handle floats… perhaps a new field type would be needed.

1 Like

Oh thanks, I keep that in mind in case I need this sometime. For now I have <10 elements so it will work with a string number. But for a start I like to keep my Framework untouched so that it is easily updatable.

@daft Yea numbers are tricky, but in general having whole numbers and floats is ok I think. Also many floats can be represented with integers. E.g. money by storing cents in the value and then recalculating it to a float with fixed decimals. Yet having a distinct difference of them is good to prevent any rounding errors.