Php – Magento ‘Select Configurable Attributes’ with PHP

magentoPHP

I have created new configurable products, and attached their simple products with PHP.

Now when I edit any configurable product I see this screen:

Magento Select Configurable Attributes screen in admin

So in absence of any Magento documentation, what do I call in PHP to perform the same function as the screen above programatically?

I have seen $configurable_product->setConfigurableProductsData() used in some examples, but don't think it is what I need.

Best Answer

You are right, you are creating the association/link between configurable and child products but what's happening is that when you are creating your configurable product you are not setting up the setConfigurableAttributesData that basically setups the superattribute information for that configurable product.

    foreach($configAttrCodes as $attrCode){

        $super_attribute= Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product',$attrCode->code);
        $configurableAtt = Mage::getModel('catalog/product_type_configurable_attribute')->setProductAttribute($super_attribute);

        $newAttributes[] = array(
           'id'             => $configurableAtt->getId(),
           'label'          => $configurableAtt->getLabel(),
           'position'       => $super_attribute->getPosition(),
           'values'         => $configurableAtt->getPrices() ? $configProduct->getPrices() : array(),
           'attribute_id'   => $super_attribute->getId(),
           'attribute_code' => $super_attribute->getAttributeCode(),
           'frontend_label' => $super_attribute->getFrontend()->getLabel(),
        );
    }

    $existingAtt = $product->getTypeInstance()->getConfigurableAttributes();

    if(empty($existingAtt) && !empty($newAttributes)){
        $configProduct->setCanSaveConfigurableAttributes(true);
        $configProduct->setConfigurableAttributesData($newAttributes);
        $configProduct->save();

    }

This is small snippet should get you there, let me know if you have any questions or need further help.