Greetings! I'm Aneesh Sreedharan, CEO of 2Hats Logic Solutions. At 2Hats Logic Solutions, we are dedicated to providing technical expertise and resolving your concerns in the world of technology. Our blog page serves as a resource where we share insights and experiences, offering valuable perspectives on your queries.
In this article, we will discuss how to show the latest products first in the list of products in a category.
We need to add a custom subscriber for ProductEvents
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | /** * class MySubscriber implements EventSubscriberInterface { /** * @var SystemConfigService */ private $systemConfigService; public function __construct( SystemConfigService $systemConfigService ) { $this->systemConfigService = $systemConfigService; } public static function getSubscribedEvents(): array { return [ ProductEvents::PRODUCT_LISTING_CRITERIA => 'productListingCriteria' ]; } public function productListingCriteria(ProductListingCriteriaEvent $event) { if ($this->systemConfigService->get(Plugin.config.sortCreatedByCategories')) { if ($this->checkCategoryFromConfig( $this->systemConfigService->get('Plugin.config.sortCreatedByCategories'), $event->getRequest()->attributes->get('navigationId')) ) { $criteria = $event->getCriteria(); $criteria->addSorting( new FieldSorting('createdAt', 'DESC') ); } } return; } function checkCategoryFromConfig($categories, $configCategory) { if(is_array($configCategory)) { return !empty(array_intersect($configCategory, $categories)); } return !empty(in_array($configCategory, $categories)); } } */ |
Here we are using the SystemConfigService to get the plugin configuration. By using that the selected category or categories in the plugin configuration are fetched.
Then we need to sort the list by the created date.
Here are the services.xml and config.xml so it makes your life easier.
1 2 3 4 5 6 | /** * <service id="PluginSubscriberMySubscriber"> <argument type="service" id="ShopwareCoreSystemSystemConfigSystemConfigService" /> <tag name="kernel.event_subscriber"/> </service> */<span id="mce_marker" data-mce-type="bookmark" data-mce-fragment="1"></span> |
1 2 3 4 5 6 7 8 9 | /** * <card> <component name="sw-entity-multi-id-select"> <name>sortCreatedByCategories</name> <entity>category</entity> <label>Choose Categories To Be Sorted Based on Creation Date</label> </component> </card */<span id="mce_marker" data-mce-type="bookmark" data-mce-fragment="1"></span> |
Hope it helps