Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting selected dropdown value for custom attribute in Magento automatically

Tags:

php

magento

I'm trying to get a custom dropdown attribute's selected value using

echo $_product->getProductSize();

and

echo $_product->getAttributeText('product_size');

Then, I clear my cache and reindex and reload my page. I tried selecting a value from the dropdown but either one returns anything. So basically, my question is, how can I retrieve the selected value from a custom dropdown attribute? I'm planning on using this to display different contents on my product page depending on the selected value. Thanks in advance for any help and advice.

Addition: I'm trying to call it on the product page where the same dropdown is called.

After trying to play with the attribute a little bit through the admin panel, I noticed how the value I selected echoed on the page. However, I was hoping of being able to retrieve it dynamically on the frontend. Is this possible? For example, in the frontend, the customer selects option B, then I would display information related to option B. Then if he changed to option D then the information would change to option D's information.

like image 970
user1597438 Avatar asked Jul 19 '13 03:07

user1597438


2 Answers

echo $_product->getAttributeText('product_size');

It should work unless your theme is dependent on this setting 'Used in Product Listing' and 'Visible on Product View Page on Front-end' for your attribute from backend in Manage Attribute. Additionally check if your attribute code does not contain any spaces. Although magento do not let you use spaces in attribute code through form submission but if attribute is created programmatically or from sql query then it is possible. Other wise it is something else not your code or attribute causing problem.

like image 149
Deependra Singh Avatar answered Oct 25 '22 02:10

Deependra Singh


Refer to this code, it might be useful.
The code fetches all custom options with their values

foreach ($_product->getOptions() as $value)
{
    echo "<br/><strong>".$value->getTitle()."</strong><br/>";
    $values = $value->getValues();// Getting Values if it has option values, case of select,dropdown,radio,multiselect
    ?>
    <select id = "<?php echo 'select_'.$value->getId() ?>" name = "<?php echo 'options['.$value->getId() .']'?>">
    <?php
    foreach ($values as $val)
        {
            echo "<option price = " . $val->getPrice(). " value = ".$val->getOptionTypeId() . ">" .$val->getTitle()."</option>";
        }
        ?>
    </select>
    <?php
    $i++; 
}

Note : The code outputs the custom options & their values just as they would be required if they were to be used for adding the product to the cart.
You can remove the select if you just want to get the option values(to reduce the complexity of the code).

like image 21
Shatir Avatar answered Oct 25 '22 02:10

Shatir