Magento 2 get attribute values - php

I have created a product attribute in Magento 2 that is a dropdown.
I have given this attribute many options. How can I output all these possible options attached to the attribute code/name? I can only find examples for Magento 1 or those that are assigned to a product. I want to get all the options assigned to the attribute.
This is what I tried before realising it wasnt for Magento 2.
<?php
$attributeId = Mage::getResourceModel(‘eav/entity_attribute’)->getIdByCode(‘catalog_product’,’color’);
$collection = Mage::getResourceModel(‘eav/entity_attribute_option_collection’)
->setPositionOrder(‘asc’)
->setAttributeFilter($attributeId)
->setStoreFilter(0)
->load();
print_r($collection->getData());
?>

you can try below code
function getAttrAllOptions() {
$eavConfig = $this->objectManager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'color');
$alloptions = $attribute->getSource()->getAllOptions();
foreach($alloptions as $option) {
$label = $option['label'];
$AllOptionsArr[$label][] = $option['value'];
}
return $AllOptionsArr;
}
hope this helps!

Related

Set default first attributes for woocommerce variations

I found this question, but no one gave a working answer:
Woocommerce Set Default Variations
What is mentioned here doesn't work anymore and I don't understand what the error is:
https://quadlayers.com/default-product-attributes-woocommerce/
Maybe someone knows how to make sure that when entering a variable product, at least some option is selected and the add to cart button is active?
The code that unfortunately no longer works:
add_action('woocommerce_before_single_product_summary', 'quadlayers_product_default_attributes');
function quadlayers_product_default_attributes() {
global $product;
if (!count($default_attributes = get_post_meta($product->get_id(), '_default_attributes'))) {
$new_defaults = array();
$product_attributes = $product->get_attributes();
if (count($product_attributes)) {
foreach ($product_attributes as $key => $attributes) {
$values = explode(',', $product->get_attribute($key));
if (isset($values[0]) && !isset($default_attributes[$key])) {
$new_defaults[$key] = sanitize_key($values[0]);
}
}
update_post_meta($product->get_id(), '_default_attributes', $new_defaults);
}
}
}
You should have the option to select a 'Default Form Values:' inside variations tab which lets you select the default option for your variant.
Like this:

How do I display an attribute on product view page in magento 2

I am trying to display some attributes on the product view page on a magento 2 website. However i am not able to get the values to echo onto the page. I have tried using
$block->getData('price')
and
$block->getAttributeText('name')
I am trying to call upon the price value and also a custom text attribute and display/use via phtml file.
Appreciate the help. Thanks
Try this:
<?php $_product = $block->getProduct();
echo $_product->getPrice();
echo $_product->getAttributeText('color');
?>
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($singleproductdata['entity_id']);
$attributes = $product->getAttributes();
foreach ($attributes as $attribute) {
echo $attribute->getAttributeCode();
echo $attribute->getFrontend()->getValue($product);
}
A quick option it is to choose a template with in Magento_Catalog/templates/product/view/form.phtml and add the following code. Otherwise you can build your own block and get it from the the catalog_product_view.xml
<?php
$attribute = $_product->getResource()->getAttribute('your-att-code');
if ($attribute)
{
$attr_value = $attribute ->getFrontend()->getValue($_product);
echo $attr_value;
}
?>

Get custom attribute from product in Magento 1.9

I'm trying to fetch some product data based on the products SKU. This is working, but I also need to get a custom added attribute at the same time, named 'sku_supplier'. Is this possible?
This is what I got:
require $_SERVER['DOCUMENT_ROOT'] . "/app/Mage.php";
Mage::app();
$sku = '748547';
$products = Mage::getResourceModel('catalog/product_collection');
$products->addAttributeToSelect('*');
$products->addAttributeToFilter('visibility', array('neq' => 1));
$products->addAttributeToFilter('status', 1);
$products->addAttributeToFilter('sku', $sku);
$products->setCurPage(1)->setPageSize(1);
$products->load();
if ($products->getFirstItem()) {
$product = $products->getFirstItem();
$strProdName = $product->getName();
$strProdSku = $product->getSku();
$strProdSkuSup = $product->getSku_Supplier(); // <= I want to show this
}else{
$addError = 'true';
$addErrorMessage[] = 'Error...';
}
Thanks in advance,
Just remove the underscore:
$strProdSkuSup = $product->getSkuSupplier();
$strProdSkuSup = $product->getData('sku_supplier'); //alternative
Magento translates snake_case into camelCase when you want to use the magic getters; ie. an attribute with the attribute code cool_custom_attribute would translate into coolCustomAttribute, i.e. $product->getCoolCustomAttribute().
Edit:
You might need to load a product model as sometimes I've experienced that not all custom attributes are attached when you pull it out of a collection (intended for performance reasons I guess). Something like:
$_product = Mage::getModel('catalog/product')->load($product->getId());
$strProdSkuSup = $_product->getSkuSupplier();
Also, did you know that there's a dedicated StackExchange site for Magento?
Use this
$strProdSkuSup = $product->getSkuSupplier();
Instead of
$strProdSkuSup = $product->getSku_Supplier();

Performing a LIKE on Magento product attribute multiselect

Is it possible to do a a LIKE operation on a multiselect attribute on a magento product collection?
For example below I am doing a find in set to locate an exact match:
$_productCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter('makemodel',
array('finset' => Mage::getResourceModel('catalog/product')
->getAttribute('makemodel')
->getSource()
->getOptionId('#Massey Ferguson##350#')
)
)
->addAttributeToSelect('*');
if($_productCollection){
foreach($_productCollection as $product){
var_dump($product->getData());
}
}
What I want to be able to do is get the option ID's for attribute options that contain #Massey Ferguson# and then find any products with the returned option ID's..
Any suggestions?
Ok so I came up with a method for doing a like against a multiselect attribute option...
$make = $make.'%';
/** #var $attribute Mage_Eav_Model_Entity_Attribute */
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getId())
->addFieldToFilter('value', array ('like' => $make))
->addFieldToSelect('option_id')
->setStoreFilter(0, false);
$set = array();
foreach($valuesCollection as $option){
$set[] = $option->getData('option_id');
}
$_productCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter('makemodel',
array('in' => $set
)
)
->addAttributeToSelect('*');
This seems to work quite well! If anybody else has a solution that might work better please let me know.

get quote's product attribute

Hi I'm trying to get a product attribute admin value or id (since it's multilanguage) from the cart items. I've tried many versions of code like this one:
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllItems() as $item) {
$_product = Mage::getModel('catalog/product')->load($item->getId());
$attribute = $_product->getAttribute('producttype');
}
But I only ever get false or null. Also how can I be sure to not get the store specific language value, but the attributes admin value/id? Maybe there's an even better way to read out the item attributes directly from the quote items without having to load the product first? Thanks in advance!
Solved with:
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllVisibleItems() as $_item)
{
$_product = Mage::getModel('catalog/product')->load($_item->getProductId());
$attributeId = $_product->getProducttype();
}
and comparing by value ID instead of text.
If you need to get the product's value for a specific shop, while the items in the quote belong to a different store view, you can do the folowing:
$_product = Mage::getModel('catalog/product')
->setStoreId($adminStoreId)
->load($item->getId());
$value = $_product->getData('producttype');

Categories