\Magento\Catalog\Model\Product\Attribute\Repository
在构造函数中注入实例(在块,帮助器类或任何地方):
/**
* @var \Magento\Catalog\Model\Product\Attribute\Repository $_productAttributeRepository
*/
protected $_productAttributeRepository;
/**
* ...
* @param \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository
* ...
*/
public function __construct(
...
\Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository,
...
) {
...
$this->_productAttributeRepository = $productAttributeRepository;
...
}
然后在您的类中创建一个方法,以通过代码获取属性:
/**
* Get single product attribute data
*
* @return Magento\Catalog\Api\Data\ProductAttributeInterface
*/
public function getProductAttributeByCode($code)
{
$attribute = $this->_productAttributeRepository->get($code);
return $attribute;
}
然后,您可以像在.phtml文件中那样调用此方法。
$attrTest = $block->getProductAttributeByCode('test');
然后,您可以调用属性对象,例如
- 获取选项:
$attribute->getOptions()
- 获取每个商店的前端标签:
$attrTest->getFrontendLabels()
- 调试数据数组:
echo '> ' . print_r($attrTest->debug(), true);
调试:数组([attribute_id] => 274 [entity_type_id] => 4 [attribute_code] => product_manual_download_label [backend_type] => varchar [frontend_input] =>文本[frontend_label] =>产品手册下载标签[is_required] => 0 [ is_user_defined] => 1 [default_value] =>产品手册下载[is_unique] => 0 [is_global] => 0 [is_visible] => 1 [is_searchable] => 0 [is_filterable] => 0 [is_comparable] => 0 [ is_visible_on_front] => 0 [is_html_allowed_on_front] => 1 [is_used_for_price_rules] => 0 [is_filterable_in_search] => 0 [used_in_product_listing] => 0 [used_for_sort_by] => 0 [is_visible_in_advanced_search] => 00 [is_wysiwyg_enabled] => 0 [is_used_for_promo_rules] => 0 [is_required_in_admin_store] => 0 [is_used_in_grid] => 1 [is_visible_in_grid] => 1 [is_filterable_in_grid] => 1 [search_weight] => 1