Magento – How to get the attribute values for multiselect in magento 2

attributesmagento-2.0multiselect-attribute

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>';
        }
      }   
    }

Best Answer

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>
Related Topic