1

I want to post this magento 1 code for magento 2

$attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product','makemulti');
     $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
     $attributeOptions = $attribute ->getSource()->getAllOptions();

This is my controller file, I have created attribute as v_models, I put the code that you have given but values are not loaded in drop down.

  <?php
    namespace Kamtech\Ymmems\Controller\Ymmemssearch;
    class Model extends \Magento\Framework\App\Action\Action
    {
     public function execute()
        {


        $obj = \Magento\Framework\App\ObjectManager::getInstance();
        $attributesList = $obj->create('Magento\Catalog\Model\Entity\Attribute')->loadByCode('catalog_product', 'v_model');

        foreach ($attributesList->getSource()->getAllOptions() as $optionInfo) {
            echo "List of Multiselect <pre>";print_r($optionInfo);exit;
            if($optionInfo['value'] != ''){
                echo $optionInfo['value'].' = '.$optionInfo['label']."<br>";
            }
        }


        foreach($this->getRequest()->getParams() as $make=>$value) {
                //echo '<dt><strong>Param: </strong>'.$make.'</dt>';
                //echo '<dt><strong>Value: </strong>'.$value.'</dt>';
            }

            if($value=="-1")
            {
            echo '<dt><strong>Param value: </strong>'.$value.'</dt>';
            echo '<select name="model"><option id=-1 value="Select Model">Select Model</option></select>';
             return;
            }
           $makeattribute_code="makes";
           $modelattribute_code="v_models";
         $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()
           ->get('Magento\Framework\App\ResourceConnection');
           $connection= $this->_resources->getConnection();
           $table1=$this->_resources->getTableName ( 'eav_attribute' );
           $table2=$this->_resources->getTableName ( 'catalog_product_entity_varchar' );
           $table3=$this->_resources->getTableName ( 'eav_attribute_option_value' );
           $table4=$this->_resources->getTableName ( 'YMME' );

           $makequery = $connection->query("select attribute_id from ".$table1." where attribute_code='".$makeattribute_code."'");
            $row = $makequery->fetch ();
            $make_attributeid=$row['attribute_id'];

           $genquery1 = $connection->query("select attribute_id from ".$table1." where attribute_code='".$modelattribute_code."'");
           $row = $genquery1->fetch ();
           $model_attributeid=$row['attribute_id'];
            //echo '<dt><strong>Model Attribute: </strong>'.$model_attributeid.'</dt>';

           $storevalues1='';
           $queryString="SELECT distinct value from ".$table2." where attribute_id=".$model_attributeid ." and entity_id in (select entity_id from ".$table2." where attribute_id=".$make_attributeid ." and value like '%".$value."%') order by value";

           echo '<dt><strong>Query: </strong>'.$queryString.'</dt>';

           $genquery2 = $connection->query("SELECT distinct value from ".$table2." where attribute_id=".$model_attributeid ." and entity_id in (select entity_id from ".$table2." where attribute_id=".$make_attributeid ." and value like '%".$value."%') order by value");


            while($rowZ = $genquery2->fetch ()){
                // echo '<dt><strong>124 Inside While loop </strong></dt>';
                if($storevalues1 == '')
                {

                }
                else
                {
                    $storevalues1=$storevalues1.',';
                }
                $storevalues1=$storevalues1.$rowZ['value'];

            }

        $make_option_value_query  =  $connection->query("SELECT value FROM ".$table3." where option_id in (".$value.")");
        $make_option_value_row = $make_option_value_query->fetch ();
        $make_option_value = $make_option_value_row['value'];

        if ($storevalues1 != '')
        {
            $genquery3 = $connection->query ("SELECT distinct option_id,value FROM ".$table3." where option_id in (".$storevalues1." )order by value");
            $fname="getResponseToDiv('year?model='+this.options[this.selectedIndex].value+'&makes='+ymme.make.value,'yeardiv',this.options[this.selectedIndex].value)";
            //  echo '<label for="Model">Model</label>';
            echo '<select id=model name=model onChange='.$fname.' ><option id=-1 value="Select Model">Select Model</option>';

           //$attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product','modelmulti');
          // $attributeId = $this->_eavAttribute->getIdByCode('catalog_product', 'v_models');
          // $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);

           //echo "<pre>"; print_r($attributeOptions); echo "</pre>";
           //echo '<option value='.'"'.$attributeOptions[$nz]['value'].'"'.' >'.$attributeOptions[$nz]['label'].' </option>';


            while($row = $genquery3->fetch ())
            {
              for($nz=1;$nz<=count($attributeOptions); $nz++)
                  {
                    $row['value']=$row['option_id'];
                    if($row['value']==$attributeOptions[$nz]['value'])
                     {
                        $ymmquery1 = $connection->query ("SELECT distinct model from ".$table4." where model ='".$attributeOptions[$nz]['label']."' and make = '".$make_option_value."' ");

                      while($row1 = $ymmquery1->fetch ())
                      {
                        $model_map=$row1['model'];

                        echo '<option value='.'"'.$row['value'].'"'.' >'.$model_map.' </option>';
                      }

                      //echo '<option id='.$attributeOptions[$nz]['value'].' value='.$row['value'].'>'.$attributeOptions[$nz]['label'].'</option>';
                     }

                  }
             }

         echo '</select>';
        }
      }   
    }
1
  • i have update your questions, please try with above code Commented Aug 24, 2016 at 11:58

4 Answers 4

7

I have alternate solution for the same, please try this one.

create block in "catalog_product_view.xml" (where you want to display attribute)

 <referenceBlock name="product.info.main">
<block class="Magento\Catalog\Block\Product\View" name="attribue.name" template="Magento_Catalog::product/view/attribute_name.phtml" after="-"  /> </referenceBlock>

create "phtml" file under "Magento_Catalog::product/view/attribute_name.phtml"

<?php $product = $block->getProduct(); ?> // Get current product
<div>
    <?php 
        $data = explode(',',$product->getData('attribute_code'));
        foreach($data as $value):            
    ?>
        <?php 
        $attr = $product->getResource()->getAttribute('attribute_code');
        if ($attr->usesSource()): ?>
            <?php 
                $option_value = $attr->getSource()->getOptionText($value);
            ?>
            <p><?php echo $option_value; ?></p>

        <?php endif;?>
    <?php endforeach;?>
</div>
1
  • I have values with commas inside and this solution is splitting single value to multiple paragraphs...
    – kovinet
    Commented Oct 11, 2020 at 10:02
0

Using Directly Objectmanger is not a proper way to get result into magento 2 using __consturct() way to best manner to use magento 2.

1st way,

$obj = \Magento\Framework\App\ObjectManager::getInstance();
    $attributesList = $obj->create('Magento\Catalog\Model\Entity\Attribute')->loadByCode('catalog_product', 'activity');

        foreach ($attributesList->getSource()->getAllOptions() as $optionInfo) {
            //echo "<pre>";print_r($optionInfo);
            if($optionInfo['value'] != '')
                echo $optionInfo['value'].' = '.$optionInfo['label']."<br>";
        }

2nd Way Using BLock

Inside Block file

    protected $attributes;
        class Getattributes{
             public function __construct(
                \Magento\Framework\View\Element\Template\Context $context,
                \Magento\Catalog\Model\Entity\AttributeFactory $attributes
                array $data = []
            ) {
                $this->attributes = $attributes;
                parent::__construct($context, $data);
            }

            public function getMultiselectlist($resourcename,$attributename){
                $attributesList = $this->attributes->loadByCode($resourcename, $attributename);
                return $attributesList;
            }
        }

call inside template file

echo $block->getMultiselectlist('catalog_product',$attributes='activity');

please let me know if any issue

1
  • i have put the code that you have given,values are not loaded ,kindly check my controller file
    – kam
    Commented Aug 24, 2016 at 10:14
0

Use this method :

$product->getAttributeText('attribite_code');

if to check implementation you will see :

https://github.com/magento/magento2/blob/ed5c06d68ec4bf77ad6c03e0af28a133b1193b66/app/code/Magento/Catalog/Model/Product.php#L1798-L1809

   /**
     * Get attribute text by its code
     *
     * @param string $attributeCode Code of the attribute
     * @return string|array|null
     */
    public function getAttributeText($attributeCode)
    {
        return $this->getResource()->getAttribute($attributeCode)->getSource()->getOptionText(
            $this->getData($attributeCode)
        );
    }

For multiple attributes use foreach to loop attributes.

As you can see Magento 2 is super not optimized and broken. It can't resolve multiple attributes because of the good design.

 /**
         * Get a text for option value
         *
         * @param  string|int $value
         * @return string|bool
         */
        public function getOptionText($value)
        {
            $options = $this->getAllOptions();
            // Fixed for tax_class_id and custom_design
            if (count($options) > 0) {
                foreach ($options as $option) {
                    if (isset($option['value']) && $option['value'] == $value) {
                        return $option['label'] ?? $option['value'];
                    }
                }
            }
            // End
            if (is_scalar($value) && isset($options[$value])) {
                return $options[$value];
            }
            return false;
        }
0
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
...
public function __construct(
    ...
    ProductResource           $productResource
)
{
    ...
    $this->productResource = $productResource;
}

public function prepareProductAttributeOptions($product, $attributeCode)
{
    $result = [];
    $data = $product->getData($attributeCode);
    $optionsIds = [];
    if ($data) {
        $optionsIds = explode(',', $data);
    }

    foreach ($optionsIds as $optionId) {
        $attr = $this->productResource->getAttribute($attributeCode);
        if ($attr->usesSource()) {
            $option_value = $attr->getSource()->getOptionText($optionId);
            $result[] = $option_value;
        }
    }

    return implode(',', $result);

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.