Magento code snippets Part I: Product model

Bei meiner täglichen Arbeit mit Magento gibt es immer wieder Code Snippets, die ich immer wieder brauche und dann google. Daher habe ich hier jetzt ein paar Snippets zusammen geschrieben um mir das googlen zu ersparen.

Load AttributeSet by name:

/**
 * Returns attribute set by name.
 * @param string $attributeSetName Attribute set name
 * @return Mage_Eav_Model_Entity_Attribute_Set Attribute set
 */
protected function getAttributeSetByName($attributeSetName) {
    $entityTypeId = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
    $attributeSet = Mage::getModel('eav/entity_attribute_set')
            ->getCollection()
            ->setEntityTypeFilter($entityTypeId)
            ->addFieldToFilter('attribute_set_name', $attributeSetName)
            ->getFirstItem();
    if (!$attributeSet->getId()) {
        return null;
    }
    return $attributeSet;
}

Load product by SKU:

/* @var $product Mage_Catalog_Model_Product */
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);

Iterate through custom options:

/* @var $product Mage_Catalog_Model_Product */
$product = Mage::getModel('catalog/product')->load(1);

if ($product->hasCustomOptions()) {
    foreach ($product->getOptions() as $option) {
        /* @var $option Mage_Catalog_Model_Product_Option */ 
        echo $option->getDefaultTitle();
    }
}

Iterate through bundle options:

$product = Mage::getModel('catalog/product')->load(1);
/* @var $product Mage_Catalog_Model_Product */

if ($product->getTypeId() === Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {

    /* @var $product_type Mage_Bundle_Model_Product_Type */
    $product_type = $product->getTypeInstance();

    /* @var $options Mage_Bundle_Model_Resource_Option_Collection */
    $options = $product_type->getOptionsCollection();

    foreach ($options as $option) {
        /* @var $options Mage_Bundle_Model_Option */
        echo "Option Title: ". $option->getDefaultTitle();
        foreach ($product_type->getSelectionsCollection(array($option->getId())) as $selection) {
            /* @var $selection Mage_Catalog_Model_Product */
            echo "Product SKU: ". $selection->getSku(); 
        }
    }
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht.

Time limit is exhausted. Please reload the CAPTCHA.