Magento - Query for Product Options

后端 未结 2 1423
无人共我
无人共我 2021-01-15 05:53

I want to write a controller that finds the different options for a given product (eg. Large, Medium, Small, Red, Blue etc...).

Can anyone show me the code I would w

2条回答
  •  旧巷少年郎
    2021-01-15 06:35

    Instead of getOptions() please try getCustomOptions() or getProductOptionsCollection() or getProductOptionsCollection()->load().

    Edit
    I tried this on a product I knew had options.

    load($productId);
    foreach ($product->getProductOptions() as $option) {
        print_r($option->debug());
    }
    

    And got something like this:

    Array
    (
        [option_id] => 37
        [product_id] => 8
        [type] => multidate
        [is_require] => 1
        [sku] => 
        [image_size_x] => 0
        [image_size_y] => 0
        [sort_order] => 1
        [default_title] => Dates
        [title] => Dates
    )
    

    However, getOptions() also worked for me so I don't know what's going on.

    Post-edit
    The confusion was one of semantics. A simple product can have "custom options", they allow creation of a few form fields which are recorded as part of the order. A configurable product uses "associated products" to create a form with conditional fields.

    For example you might be selling socks that are large-green, small-green or large-blue - but no small-blue ones. With a simple product you would have a field for large/small and a field for blue/green - which allows the customer to select small-blue and that is wrong.

    So to find the component parts of a configurable you might do something like this:

    if ($product->isConfigurable()) {
        $configurable = $product->getTypeInstance();
        $childProducts = $product->getUsedProducts($product);
        foreach ($childProducts as $child) {
            // You have a $child now
        }
    }
    

    To find the equivalent of getOptions() you need this:

    if ($product->isConfigurable()) {
        $configurable = $product->getTypeInstance();
        $attributes = $configurable->getConfigurableAttributes($product);
        // $attributes is a Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Type_Configurable_Attribute_Collection
        foreach ($attributes as $attribute) {
            // $attribute is a Mage_Catalog_Model_Product_Type_Configurable_Attribute
            print $attribute->getLabel();
        }
    }
    

    Mage_Catalog_Model_Product_Type_Configurable_Attribute doesn't have much to reveal about itself.

提交回复
热议问题