magento / magento2

Prior to making any Submission(s), you must sign an Adobe Contributor License Agreement, available here at: https://opensource.adobe.com/cla.html. All Submissions you make to Adobe Inc. and its affiliates, assigns and subsidiaries (collectively “Adobe”) are subject to the terms of the Adobe Contributor License Agreement.
http://www.magento.com
Open Software License 3.0
11.37k stars 9.28k forks source link

Catalog Swatch Helper Data Access #38887

Open kestraly opened 1 week ago

kestraly commented 1 week ago

Preconditions and environment

Magento 2.4.x

Accessing the catalog swatch helper data directly from templates is not possible. Is there a reason this is not possible?

Steps to reproduce

Add $this->helper('Magento\Swatches\Helper\Data'); in a .phtml template file that is loaded on a catalog page.

Sample Code

$swatchHelper = $this->helper('Magento\Swatches\Helper\Data');

$color_attribute = $_product->getResource()->getAttribute('color');
$color_options = $color_attribute ? $color_attribute->getSource()->getAllOptions() : [];
$colorOptionIds = [];
foreach ($color_options as $color_option) {
    if ($color_option['value']) {
        $colorOptionIds[] = $color_option['value'];
    }
}
$swatchHelper->getSwatchesByOptionsId($colorOptionIds);

Expected result

Access to Catalog Swatch Helper Data to perform tasks such as

Actual result

main.ERROR: Magento\Swatches\Helper\Data doesn't extends Magento\Framework\App\Helper\AbstractHelper when accessing a page using the .phtml template file.

Additional information

Possible solution for Helper vendor/magento/module-swatches/Helper/Data.php

Update from class Data

to

class Data extends \Magento\Framework\App\Helper\AbstractHelper

Release note

No response

Triage and priority

m2-assistant[bot] commented 1 week ago

Hi @kestraly. Thank you for your report. To speed up processing of this issue, make sure that the issue is reproducible on the vanilla Magento instance following Steps to reproduce. To deploy vanilla Magento instance on our environment, Add a comment to the issue:

m2-assistant[bot] commented 5 days ago

Hi @engcom-Hotel. Thank you for working on this issue. In order to make sure that issue has enough information and ready for development, please read and check the following instruction: :point_down:

engcom-Hotel commented 5 days ago

Hello @kestraly,

Thanks for the report and collaboration!

It seems to us an expected behavior, If you still need to use the methods from Magento\Swatches\Helper\Data in your .phtml file, you should create a ViewModel and use dependency injection to get the Magento\Swatches\Helper\Data class. Then, you can create a method in your ViewModel that uses the methods from the helper. You can then call this method from your .phtml file.

Else please let us know your use case if you don't want to create a ViewModel.

Thanks