oc-shopaholic / oc-shopaholic-plugin

🛍️ No. 1 e-commerce platform for October CMS
https://shopaholic.one
GNU General Public License v3.0
425 stars 52 forks source link

Sorting products by column #97

Closed philmarc closed 6 years ago

philmarc commented 6 years ago

I have a ProductList like so: {% set obProductList = ProductList.make().sort('new').active() %}

Available sorting are : 'new' 'price|asc' 'price|desc'

What if I want to order products by external_id or any other model column ?

In Blade I would do {{ $obProductList = $products->where('active', 1)->orderBy('external_id', ASC)->get() }}

How to do that with twig? Or should I extend the SortingListStore?

kharanenka commented 6 years ago

Hi! You can listen event 'shopaholic.sorting.get.list'. For example:

Event::listen('shopaholic.sorting.get.list', function($sSorting) {
    if ($sSorting != 'my_sorting') {
        return null;
    }

    //Get array with product ID
    $arResult = [2,4,67,8];
    return $arResult;
});

You need add method for cache clearing of your custom sorting


use Lovata\Shopaholic\Classes\Store\ProductListStore;

ProductListStore::instance()->sorting->clear('my_sorting');
philmarc commented 6 years ago

Thanks for your help, it works fine. Here is what I did:

// plugins/lovata/shopaholic/Plugin.php

use Lovata\Shopaholic\Models\Product;

public function boot()
{
    $this->addEventListener();
    Event::listen('shopaholic.sorting.get.list', function($sSorting) {
        if ($sSorting != 'specific') {
            return null;
        }
        $arElementIDList = (array) Product::orderBy('external_id', 'asc')->lists('id');
        $arElementIDList = array_unique($arElementIDList);
        return $arElementIDList;
    });
}

And to clear the cache

// plugins/lovata/shopaholic/classes/event/ProductModelHandler.php;

protected function afterSave()
{
    ProductListStore::instance()->sorting->clear('specific');
}

PS: I hope it's not gonna be erased if there is an update in those files?

kharanenka commented 6 years ago

Your changes will be overwritten when you update plugin, you need to add this code to your own custom project plugin.