0

I have an Element. It's a Structure, with one level (not sure if that is relevant). I'd like to add a Sort Option that allows a user to sort the Element Index page for this Element by a number. The number attribute is stored in the database as an int and named count.

On the Element class, I can add a way to sort the Element by a row alphabetically:

protected static function defineSortOptions(): array
{
  $attributes = [
    'someTextField' => Craft::t('my-plugin', 'Some Text Field')
  ]
}

However, I haven't yet been able to figure out how to give the option to sort by a number:

protected static function defineSortOptions(): array
{
  $attributes = [
    'someTextField' => Craft::t('my-plugin', 'Some Text Field'),
    'count' => Craft::t('my-plugin', 'Count')
  ]
}

The above example does not work. I've also explored the non-shorthand syntax that I see in the Craft Commerce Subscription sort options, however, have been unable to figure out how to adjust things to work with numbers.

protected static function defineSortOptions(): array
{
    return [
        [
            'label' => Craft::t('commerce', 'Subscription date'),
            'orderBy' => 'commerce_subscriptions.dateCreated',
            'attribute' => 'dateCreated'
        ],
    ];
}

How can I allow a user to order an Element Index page by a numeric column?

  • Did you define count as tableattribute as well? – Robin Schambach Feb 23 at 18:24
  • Yep. public static function defineTableAttributes($source = null): array { return [ 'count' => Craft::t('my-plugin', 'Count') ]; } – Ben Parizek Feb 24 at 22:26
  • 1
    I'm not totally sure if that's really the issue but maybe it could have something to do with the word count in yii2 and queries. I'll investigate more time in a few hours but maybe you could try to rename it to count2 or something else and see if it solves the issue. In general there is no difference between text and number columns in the DB. Just a question for now: what didn't work? Was the column not sortable or did it throw an exception? – Robin Schambach Feb 24 at 23:01
  • No errors, It's just that the column does not sort anything. It always displays the same order. – Ben Parizek Feb 25 at 0:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.