public function testReset() { $model = $this->_model; $testCase = $this; $assertEmpty = function () use($model, $testCase) { $testCase->assertEquals(array(), $model->getData()); $testCase->assertEquals(null, $model->getOrigData()); $testCase->assertEquals(array(), $model->getCustomOptions()); // impossible to test $_optionInstance $testCase->assertEquals(array(), $model->getOptions()); $testCase->assertFalse($model->canAffectOptions()); // impossible to test $_errors }; $assertEmpty(); $this->_model->setData('key', 'value'); $this->_model->reset(); $assertEmpty(); $this->_model->setOrigData('key', 'value'); $this->_model->reset(); $assertEmpty(); $this->_model->addCustomOption('key', 'value'); $this->_model->reset(); $assertEmpty(); $this->_model->addOption(new Mage_Catalog_Model_Product_Option()); $this->_model->reset(); $assertEmpty(); $this->_model->canAffectOptions(true); $this->_model->reset(); $assertEmpty(); }
/** * After attribute is saved upload file to media * folder and save it to its associated product. * * @param Mage_Catalog_Model_Product $object * @return Jvs_FileAttribute_Model_Attribute_Backend_File */ public function afterSave($object) { $value = $object->getData($this->getAttribute()->getName()); if (is_array($value) && !empty($value['delete'])) { $object->setData($this->getAttribute()->getName(), ''); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); return; } try { $uploadedFile = new Varien_Object(); $uploadedFile->setData('name', $this->getAttribute()->getName()); $uploadedFile->setData('allowed_extensions', array('jpg', 'jpeg', 'gif', 'png', 'tif', 'tiff', 'mpg', 'mpeg', 'mp3', 'wav', 'pdf', 'txt')); Mage::dispatchEvent('jvs_fileattribute_allowed_extensions', array('file' => $uploadedFile)); $uploader = new Mage_Core_Model_File_Uploader($this->getAttribute()->getName()); $uploader->setAllowedExtensions($uploadedFile->getData('allowed_extensions')); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); $uploader->save(Mage::getBaseDir('media') . '/catalog/product'); } catch (Exception $e) { return $this; } $fileName = $uploader->getUploadedFileName(); if ($fileName) { $object->setData($this->getAttribute()->getName(), $fileName); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); } return $this; }
/** * @covers Mage_Catalog_Model_Product::getCalculatedFinalPrice * @covers Mage_Catalog_Model_Product::getMinimalPrice * @covers Mage_Catalog_Model_Product::getSpecialPrice * @covers Mage_Catalog_Model_Product::getSpecialFromDate * @covers Mage_Catalog_Model_Product::getSpecialToDate * @covers Mage_Catalog_Model_Product::getRequestPath * @covers Mage_Catalog_Model_Product::getGiftMessageAvailable * @covers Mage_Catalog_Model_Product::getRatingSummary * @dataProvider getObsoleteGettersDataProvider * @param string $key * @param string $method */ public function testGetObsoleteGetters($key, $method) { $value = uniqid(); $this->assertEmpty($this->_model->{$method}()); $this->_model->setData($key, $value); $this->assertEquals($value, $this->_model->{$method}()); }
public function getUrl(Mage_Catalog_Model_Product $product, $params = array()) { if (Mage::getVersion() >= 1.8) { $product->setData('url', ''); } return parent::getUrl($product, $params); }
protected function modifyProduct(\Mage_Catalog_Model_Product $product, \Zend_Config $settings) { foreach ($settings as $attribute => $value) { $product->setData($attribute, $value); Logger::log('* change attribute <comment>%s</comment> of product #%d: "%s"', array($attribute, $product->getId(), $value)); } $product->save(); }
public static function productMediaFixture() { $product = new Mage_Catalog_Model_Product(); $product->load(1); $product->setTierPrice(array()); $product->setData('media_gallery', array('images' => array(array('file' => '/m/a/magento_image.jpg')))); $product->save(); }
/** * get the longest url for a product * from http://magento.stackexchange.com/questions/52969/get-product-path-from-id-with-category-path-in-url * @param Mage_Catalog_Model_Product|null $product [description] * @return String full url of the product */ public static function getFullProductUrl(Mage_Catalog_Model_Product $product = null) { // Force display deepest child category as request path. $categories = $product->getCategoryCollection(); $deepCatId = 0; $path = ''; $productPath = false; foreach ($categories as $category) { // Look for the deepest path and save. if (substr_count($category->getData('path'), '/') > substr_count($path, '/')) { $path = $category->getData('path'); $deepCatId = $category->getId(); } } // Load category. $category = Mage::getModel('catalog/category')->load($deepCatId); // Remove .html from category url_path. $categoryPath = str_replace('.html', '', $category->getData('url_path')); // Get product url path if set. $productUrlPath = $product->getData('url_path'); // Get product request path if set. $productRequestPath = $product->getData('request_path'); // If URL path is not found, try using the URL key. if ($productUrlPath === null && $productRequestPath === null) { $productUrlPath = $product->getData('url_key'); } // Now grab only the product path including suffix (if any). if ($productUrlPath) { $path = explode('/', $productUrlPath); $productPath = array_pop($path); } elseif ($productRequestPath) { $path = explode('/', $productRequestPath); $productPath = array_pop($path); } // Now set product request path to be our full product url including deepest category url path. if ($productPath !== false) { if ($categoryPath) { // Only use the category path is one is found. $product->setData('request_path', $categoryPath . '/' . $productPath); } else { $product->setData('request_path', $productPath); } } return $product->getProductUrl(); }
/** * Before attribute save prepare data * * @param Mage_Catalog_Model_Product $object * @return Enterprise_TargetRule_Model_Catalog_Product_Attribute_Backend_Rule */ public function beforeSave($object) { $attributeName = $this->getAttribute()->getName(); $useDefault = $object->getData($attributeName . '_default'); if ($useDefault == 1) { $object->setData($attributeName, null); } return $this; }
/** * Implode data for validation * * @param Mage_Catalog_Model_Product $object * @return bool */ public function validate($object) { $attributeCode = $this->getAttribute()->getAttributeCode(); $data = $object->getData($attributeCode); if (is_array($data)) { $object->setData($attributeCode, implode(',', array_filter($data))); } return parent::validate($object); }
public function addCustomer($data) { $connection = Mage::getModel('core/resource')->getConnection('core_read'); $product = new Mage_Catalog_Model_Product(); $product->setAttributeSetId(Mage::getModel('eav/entity_attribute_set')->getCollection()->setEntityTypeFilter($this->typeId)->addFieldToFilter('attribute_set_name', $data['attribute_set_id'])->getFirstItem()->getAttributeSetId()); unset($data['attribute_set_id']); $product->setWebsiteIDs(array(1)); //// assign product to the default website $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); $product->setStoreIDs(array(1)); foreach ($data as $key => $value) { switch ($key) { case 'store_id': case 'website_id': break; case 'status': switch ($value) { case 'Enabled': $val = 1; break; case 'Disabled': $val = 2; break; default: $val = ''; } $product->setData($key, $val); break; default: in_array($key, $this->attrsWithOpts) ? $product->setData($key, $this->optByCode($key, $value)) : $product->setData($key, $value); } } //unset($value); $product->setIsMassupdate(false); $product->setExcludeUrlRewrite(true); try { $product->save(); //Mage::getResourceSingleton('catalog/product_indexer_price')->reindexProductIds(array($productId)); } catch (Exception $ex) { mage::D($ex); #mage::log($ex->getMessage(), null, 'prodsimp.log'); } }
/** * @param Mage_Catalog_Model_Product $product * @param $productSubscriptionsData * @param $storeId * @throws Exception */ protected function _updateProductSubscriptions(Mage_Catalog_Model_Product $product, $productSubscriptionsData, $storeId) { if (!$productSubscriptionsData) { if ($product->getData('adyen_subscription_type') != Adyen_Subscription_Model_Product_Subscription::TYPE_DISABLED) { $product->setData('adyen_subscription_type', Adyen_Subscription_Model_Product_Subscription::TYPE_DISABLED); Mage::getSingleton('adminhtml/session')->addNotice(Mage::helper('adyen_subscription')->__('Adyen Subscription Type is set back to \'Disabled\' because no subscriptions were defined')); } return; } /** @var array $productSubscriptionIds */ $productSubscriptionCollection = Mage::getModel('adyen_subscription/product_subscription')->getCollection()->addFieldToFilter('product_id', $product->getId()); $isGlobal = Mage::app()->isSingleStoreMode(); if (!$isGlobal && (int) $storeId) { /** @var $website Mage_Core_Model_Website */ $website = Mage::app()->getStore($storeId)->getWebsite(); $productSubscriptionCollection->addFieldToFilter('website_id', $website->getId()); } $productSubscriptionIds = $productSubscriptionCollection->getAllIds(); $resource = Mage::getSingleton('core/resource'); $connection = $resource->getConnection('core_write'); $i = 1; // Save subscriptions foreach ($productSubscriptionsData as $id => $subscriptionData) { $subscription = Mage::getModel('adyen_subscription/product_subscription')->load($id); if (!$subscription->getId()) { $subscription->setProductId($product->getId()); } if (!isset($subscriptionData['use_default']) && $storeId) { // Save store label $labelData = array('label' => $subscriptionData['label'], 'subscription_id' => $subscription->getId(), 'store_id' => $storeId); $connection->insertOnDuplicate($resource->getTableName('adyen_subscription/product_subscription_label'), $labelData, array('label')); unset($subscriptionData['label']); } if (isset($subscriptionData['use_default']) && $storeId) { // Delete store label $connection->delete($resource->getTableName('adyen_subscription/product_subscription_label'), array('subscription_id = ?' => $subscription->getId(), 'store_id = ?' => $storeId)); } if ($subscriptionData['customer_group_id'] == '') { $subscriptionData['customer_group_id'] = null; } $subscription->addData($subscriptionData); $subscription->setSortOrder($i * 10); if (in_array($id, $productSubscriptionIds)) { $productSubscriptionIds = array_diff($productSubscriptionIds, array($id)); } $subscription->save(); $i++; } // Delete subscriptions foreach ($productSubscriptionIds as $subscriptionId) { Mage::getModel('adyen_subscription/product_subscription')->setId($subscriptionId)->delete(); } }
/** * Sets missing product Attributes for virutal product * * @param Mage_Catalog_Model_Product $product * @return Mage_Catalog_Model_Product */ public function prepareShopgateCouponProduct(Mage_Catalog_Model_Product $product) { $product->setData('weight', 0); $product->setData('tax_class_id', $this->_getTaxClassId()); $product->setData('attribute_set_id', $this->_getAttributeSetId()); $product->setData('stock_data', $this->_getStockData()); $product->setData('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE); $product->setData('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED); $product->setData('type_id', Mage_Catalog_Model_Product_Type::TYPE_VIRTUAL); return $product; }
/** * @param Mage_Catalog_Model_Product $product */ protected function _attributes(Mage_Catalog_Model_Product &$product) { $_attributes = $product->getAttributes(); /** @var Mage_Eav_Model_Entity_Attribute $attribute */ foreach ($_attributes as $attribute) { if ($attribute->getBackendType() == self::ATTRIBUTE_TYPE_TO_PREPARE) { $attributeText = $product->getAttributeText($attribute->getAttributeCode()); //getting attribute value $product->setData($attribute->getAttributeCode(), $attributeText); //setting this to product (override existing integer value) } } }
function setData($key, $value = null) { if (is_array($key)) { if (isset($key['id'])) { $this->setId($key['id']); } if (isset($key['entity_id'])) { $this->setId($key['entity_id']); } } elseif ('id' == $key || 'entity_id' == $key) { $this->vf_product->setId($value); } return parent::setData($key, $value); }
/** * Retrieve a splash page for the product / attribute code combination * * @param Mage_Catalog_Model_Product $product * @param $attributeCode * @return Fishpig_AttributeSplash_Model_Splash|null */ public function getProductSplashPage(Mage_Catalog_Model_Product $product, $attributeCode) { $key = $attributeCode . '_splash_page'; if (!$product->hasData($key)) { $product->setData($key, false); $collection = Mage::getResourceModel('attributeSplash/page_collection')->addStoreFilter(Mage::app()->getStore())->addAttributeCodeFilter($attributeCode)->addProductFilter($product)->setPageSize(1)->setCurPage(1)->load(); if (count($collection) > 0) { $page = $collection->getFirstItem(); if ($page->getId()) { $product->setData($key, $page); } } } return $product->getData($key); }
/** * @param Mage_Catalog_Model_Product $product * @return boolean */ protected function _changeUrlKey(Mage_Catalog_Model_Product &$product) { if ($product->getCategoryId() || !$this->_getHelper()->isUrlRewriteEnable()) { return false; } //if category already exist or rewrite categories is disabled $categoryIds = $product->getCategoryIds(); $categoryId = null; $product->setData("request_path", null); /** Process categories if they exists */ if (is_array($categoryIds) && count($categoryIds)) { $categoryId = $categoryIds[count($categoryIds) - 1]; //get the last element } return $this->_getUrlModel()->getProductUrl($product, null, $categoryId); }
/** * Format url_key value * * @param Mage_Catalog_Model_Product $object * @return Mage_Catalog_Model_Product_Attribute_Backend_Urlkey */ public function beforeSave($object) { $attributeName = $this->getAttribute()->getName(); $urlKey = $object->getData($attributeName); if ($urlKey === false) { return $this; } if ($urlKey == '') { $urlKey = $object->getName(); } $urlKey = $object->formatUrlKey($urlKey); if (empty($urlKey)) { $urlKey = Mage::helper('core')->uniqHash(); } $object->setData($attributeName, $urlKey); $this->_validateUrlKey($object); return $this; }
public function testReset() { $model = $this->_model; $this->_assertEmpty($model); $this->_model->setData('key', 'value'); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->setOrigData('key', 'value'); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->addCustomOption('key', 'value'); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->addOption(new Mage_Catalog_Model_Product_Option()); $this->_model->reset(); $this->_assertEmpty($model); $this->_model->canAffectOptions(true); $this->_model->reset(); $this->_assertEmpty($model); }
/** * @magentoDataFixture Mage/Catalog/_files/product_simple.php */ public function testBeforeSave() { $product = new Mage_Catalog_Model_Product(); $product->load(1); // fixture $product->setData('links_purchased_separately', 'value'); // this attribute is applicable only for downloadable $this->_model->beforeSave($product); $this->assertTrue($product->canAffectOptions()); $this->assertFalse($product->hasData('links_purchased_separately')); }
public function importProducts($products, $storeId, $store) { Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); if (!empty($products)) { foreach ($products as $_product) { $update = false; if ($_product["code"]) { $sku = $_product["code"]; } elseif ($_product["code2"]) { $sku = $_product["code2"]; } else { $sku = $_product["code3"]; } $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku); if (!$product) { $product = Mage::getModel('catalog/product')->load($_product["productID"]); if (!$product->getName()) { $product = new Mage_Catalog_Model_Product(); $product->setId($_product["productID"]); Mage::helper('Erply')->log("Creating new product: " . $_product["productID"]); } else { Mage::helper('Erply')->log("Editing old product: " . $_product["productID"]); $update = true; } } else { $update = true; } if ($_product["displayedInWebshop"] == 0) { if ($update) { try { $product->delete(); Mage::helper('Erply')->log("Delete existing product which should be in webshop id: " . $_product["productID"] . " - sku: " . $sku); } catch (Exception $e) { Mage::helper('Erply')->log("Failed to delete product with message: " . $e->getMessage()); } } continue; } $product->setStoreId($storeId); // product does not exist so we will be creating a new one. $product->setIsMassupdate(true); $product->setExcludeUrlRewrite(true); $product->setTypeId('simple'); $product->setWeight(1.0); $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); $product->setStatus(1); $product->setSku($sku); $product->setTaxClassId(0); // set the rest of the product information here that can be set on either new/update if (!$update) { $product->setAttributeSetId((int) Mage::getStoreConfig('eepohs_erply/product/attribute_set', $storeId)); // the product attribute set to use } $product->setName($_product["name"]); $category = Mage::getModel('catalog/category')->load($_product["groupID"]); if ($category->getName()) { $product->setCategoryIds(array($_product["groupID"])); // array of categories it will relate to } if (Mage::app()->isSingleStoreMode()) { $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsiteId())); } else { $product->setWebsiteIds(array($store->getWebsiteId())); } $product->setBatchPrices(array()); $product->setStockPriorities(array()); //$product->setPrice($_product["price"]); // set the product images as such // $image is a full path to the image. I found it to only work when I put all the images I wanted to import into the {magento_path}/media/catalog/products - I just created my own folder called import and it read from those images on import. // $image = '/path/to/magento/media/catalog/products/import/image.jpg'; // // $product->setMediaGallery (array('images'=>array (), 'values'=>array ())); // $product->addImageToMediaGallery ($image, array ('image'), false, false); // $product->addImageToMediaGallery ($image, array ('small_image'), false, false); // $product->addImageToMediaGallery ($image, array ('thumbnail'), false, false); // setting custom attributes. for example for a custom attribute called special_attribute // special_attribute will be used on all examples below for the various attribute types //$product->setSpecialAttribute('value here'); // setting a Yes/No Attribute // $product->setSpecialField(1); // setting a Selection Attribute //$product->setSpecialAttribute($idOfAttributeOption); //specify the ID of the attribute option, eg you creteated an option called Blue in special_attribute it was assigned an ID of some number. Use that number. // setting a Mutli-Selection Attribute //$data['special_attribute'] = '101 , 102 , 103'; // coma separated string of option IDs. As ID , ID (mind the spaces before and after coma, it worked for me like that) // $product->setData($data); if (isset($_product["attributes"])) { $erplyAttributes = $_product["attributes"]; $mapping = unserialize(Mage::getStoreConfig('eepohs_erply/product/attributes', $storeId)); if (!empty($erplyAttributes) && !empty($mapping)) { $mappings = array(); foreach ($mapping as $map) { $mappings[$map["erply_attribute"]] = $map["magento_attribute"]; } foreach ($erplyAttributes as $attribute) { if (in_array($attribute["attributeName"], array_keys($mappings))) { if ($attribute["attributeValue"]) { $product->setData($mappings[$attribute["attributeName"]], $attribute["attributeValue"]); } } } } } $product->save(); Mage::helper('Erply')->log("Added: " . $product->getSku()); } } }
/** * Add price index to bundle product after load * * @param Mage_Catalog_Model_Product $product * @return Mage_Bundle_Model_Price_Index */ public function addPriceIndexToProduct($product) { $websiteId = $product->getStore()->getWebsiteId(); $groupId = Mage::getSingleton('customer/session')->getCustomerGroupId(); $prices = $this->_getResource()->loadPriceIndex($product->getId(), $websiteId, $groupId); if (isset($prices[$product->getId()])) { $product->setData('_price_index', true)->setData('_price_index_min_price', $prices[$product->getId()]['min_price'])->setData('_price_index_max_price', $prices[$product->getId()]['max_price']); } return $this; }
/** * Set media attribute value * * @param Mage_Catalog_Model_Product $product * @param string|array $mediaAttribute * @param string $value * @return Mage_Catalog_Model_Product_Attribute_Backend_Media */ public function setMediaAttribute(Mage_Catalog_Model_Product $product, $mediaAttribute, $value) { $mediaAttributeCodes = array_keys($product->getMediaAttributes()); if (is_array($mediaAttribute)) { foreach ($mediaAttribute as $atttribute) { if (in_array($atttribute, $mediaAttributeCodes)) { $product->setData($atttribute, $value); } } } elseif (in_array($mediaAttribute, $mediaAttributeCodes)) { $product->setData($mediaAttribute, $value); } return $this; }
/** * Set additional data before product save * * @param Mage_Catalog_Model_Product $product * @param array $productData */ protected function _prepareDataForSave($product, $productData) { if (isset($productData['stock_data'])) { if (!$product->isObjectNew() && !isset($productData['stock_data']['manage_stock'])) { $productData['stock_data']['manage_stock'] = $product->getStockItem()->getManageStock(); } $this->_filterStockData($productData['stock_data']); } else { $productData['stock_data'] = array('use_config_manage_stock' => 1, 'use_config_min_sale_qty' => 1, 'use_config_max_sale_qty' => 1); } $product->setStockData($productData['stock_data']); // save gift options $this->_filterConfigValueUsed($productData, array('gift_message_available', 'gift_wrapping_available')); if (isset($productData['use_config_gift_message_available'])) { $product->setData('use_config_gift_message_available', $productData['use_config_gift_message_available']); if (!$productData['use_config_gift_message_available'] && $product->getData('gift_message_available') === null) { $product->setData('gift_message_available', (int) Mage::getStoreConfig(Mage_GiftMessage_Helper_Message::XPATH_CONFIG_GIFT_MESSAGE_ALLOW_ITEMS, $product->getStoreId())); } } if (isset($productData['use_config_gift_wrapping_available'])) { $product->setData('use_config_gift_wrapping_available', $productData['use_config_gift_wrapping_available']); if (!$productData['use_config_gift_wrapping_available'] && $product->getData('gift_wrapping_available') === null) { $xmlPathGiftWrappingAvailable = 'sales/gift_options/wrapping_allow_items'; $product->setData('gift_wrapping_available', (int) Mage::getStoreConfig($xmlPathGiftWrappingAvailable, $product->getStoreId())); } } if (isset($productData['website_ids']) && is_array($productData['website_ids'])) { $product->setWebsiteIds($productData['website_ids']); } // Create Permanent Redirect for old URL key if (!$product->isObjectNew() && isset($productData['url_key']) && isset($productData['url_key_create_redirect'])) { $product->setData('save_rewrites_history', (bool) $productData['url_key_create_redirect']); } /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */ foreach ($product->getTypeInstance(true)->getEditableAttributes($product) as $attribute) { //Unset data if object attribute has no value in current store if (Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID !== (int) $product->getStoreId() && !$product->getExistsStoreValueFlag($attribute->getAttributeCode()) && !$attribute->isScopeGlobal()) { $product->setData($attribute->getAttributeCode(), false); } if ($this->_isAllowedAttribute($attribute)) { if (isset($productData[$attribute->getAttributeCode()])) { $product->setData($attribute->getAttributeCode(), $productData[$attribute->getAttributeCode()]); } } } }
/** * Update product links for the given type of links - up sell, related, cross sell * @param Mage_Catalog_Model_Product $product Product to add links to * @param array $linkUpdates Product links data * @param string $linkType Type of product links to create * @return array Any links that could not be added */ protected function _linkProducts(Mage_Catalog_Model_Product $product, $linkUpdates, $linkType) { $opFilter = function ($operation) { return function ($el) use($operation) { return strtolower($el['operation_type']) === $operation; }; }; $skuMap = function ($link) { return $link['link_to_unique_id']; }; // get all currently linked products of this link type $linkedProductsGetter = $this->_linkTypes[$linkType]['linked_products_getter_method']; $linkedProducts = $product->{$linkedProductsGetter}(); // remove any links that are supposed to be getting deleted $deleteSkus = array_map($skuMap, array_filter($linkUpdates, $opFilter('delete'))); $linkedProducts = array_filter($linkedProducts, function ($prod) use($deleteSkus) { return !in_array($prod->getSku(), $deleteSkus); }); $addSkus = array_map($skuMap, array_filter($linkUpdates, $opFilter('add'))); // Go through the skus to add and look up the product id for each one. // If any are missing, add the product link for that sku to a list of links that // cannot be resolved yet. $missingLinks = array(); $idsToAdd = array(); foreach ($addSkus as $sku) { $linkProduct = $this->_products->getItemByColumnValue('sku', $sku); $id = $linkProduct ? $linkProduct->getId() : null; if ($id) { $idsToAdd[] = $id; } else { $missingLinks[] = $this->_buildProductLinkForSku($sku, $linkType, 'Add'); } } // get a list of all products that should be linked $linkIds = array_filter(array_unique(array_merge(array_map(function ($prod) { return $prod->getId(); }, $linkedProducts), $idsToAdd))); $linkData = array(); foreach ($linkIds as $id) { $linkData[$id] = array('position' => ''); } // add the updated links to the product $product->setData($this->_linkTypes[$linkType]['data_attribute'], $linkData); // return links that were not resolved return $missingLinks; }
/** * @param Mage_Catalog_Model_Product $product * @throws InvalidArgumentException */ public function applyPrice(Mage_Catalog_Model_Product &$product) { if ($this->_priceChild === null) { throw new InvalidArgumentException("Price child was not set"); } if ($this->_isPriceSet) { $product->setPrice($this->_price); $product->setSpecialPrice($this->_specialPrice); $product->setSpecialFromDate($this->_specialFrom); $product->setSpecialToDate($this->_specialTo); // set additional fields set in config $additionalFields = self::getAdditionalFields(); foreach ($additionalFields as $fieldName) { $product->setData($fieldName, $this->_priceChild->getData($fieldName)); } /** * Trigger event */ Mage::dispatchEvent('configurableautopricing_after_apply_price', array('parent' => $product, 'child' => $this->_priceChild)); } }
/** * Update image in gallery * * @param Mage_Catalog_Model_Product $product * @param sting $file * @param array $data * @return Mage_Catalog_Model_Product_Attribute_Backend_Media */ public function updateImage(Mage_Catalog_Model_Product $product, $file, $data) { $fieldsMap = array('label' => 'label', 'position' => 'position', 'associated_attributes' => 'associated_attributes', 'disabled' => 'disabled', 'exclude' => 'disabled'); $attrCode = $this->getAttribute()->getAttributeCode(); $mediaGalleryData = $product->getData($attrCode); if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) { return $this; } foreach ($mediaGalleryData['images'] as &$image) { if ($image['file'] == $file) { foreach ($fieldsMap as $mappedField => $realField) { if (isset($data[$mappedField])) { $image[$realField] = $data[$mappedField]; } } } } $product->setData($attrCode, $mediaGalleryData); return $this; }
/** * Retrieve bundle options collection based on ids * * @param array $optionIds * @param Mage_Catalog_Model_Product $product * @return Mage_Bundle_Model_Resource_Option_Collection */ public function getOptionsByIds($optionIds, $product) { sort($optionIds); $usedOptions = $product->getData($this->_keyUsedOptions); $usedOptionsIds = $product->getData($this->_keyUsedOptionsIds); if (!$usedOptions || serialize($usedOptionsIds) != serialize($optionIds)) { $usedOptions = Mage::getModel('Mage_Bundle_Model_Option')->getResourceCollection()->setProductIdFilter($product->getId())->setPositionOrder()->joinValues(Mage::app()->getStore()->getId())->setIdFilter($optionIds); $product->setData($this->_keyUsedOptions, $usedOptions); $product->setData($this->_keyUsedOptionsIds, $optionIds); } return $usedOptions; }
public function createBundleProduct(&$item, $asid) { $attributeSetModel = Mage::getModel('eav/entity_attribute_set'); $attributeSetModel->load($asid); if (count($attributeSetModel) > 0) { $p_status = (string) $item->isActive == 'Y' ? 1 : 2; $p_taxclass = (string) $item->isTaxable == 'Y' ? 2 : 0; $product = new Mage_Catalog_Model_Product(); $product->setTypeId('bundle'); $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); //New and created data code start $format = 'Y-m-d H:i:s'; $catalogNewproductDays = Mage::getStoreConfig('catalog/newproduct/days', Mage::app()->getStore()); if (!empty($catalogNewproductDays) && $catalogNewproductDays >= 0) { $currenDateTime = date("Y-m-d H:i:s", Mage::getModel('core/date')->timestamp(time())); $new_from_date = date($format, strtotime('1 days' . $currenDateTime)); $new_to_date = date($format, strtotime($catalogNewproductDays . ' days' . $new_from_date)); $product->setNewsFromDate($new_from_date); $product->setNewsToDate($new_to_date); } if ($product->getCreatedTime == NULL || $product->getUpdateTime() == NULL) { $product->setCreatedTime($currenDateTime)->setUpdateTime($currenDateTime); } //New and created data code end $product->setSku((string) $item->id); //Product custom id $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); $product->setStoreIDs(array($this->_store_id)); // Default store id . $product->setAttributeSetId($asid); $product->setData('name', (string) $item->name); $product->setPrice((double) $item->price); $splAmt = (array) $item->specialPrice->amount; if (isset($item->specialPrice->amount) && $item->specialPrice->amount != NULL) { if (!empty($splAmt)) { $product->setSpecialPrice((double) $item->specialPrice->amount); } //special price in form 11.22 } $fromDate = (array) $item->specialPrice->fromDateTime; if (isset($item->specialPrice->fromDateTime) && $item->specialPrice->fromDateTime != NULL) { if (!empty($fromDate)) { $product->setSpecialFromDate(Mage::helper('customimport')->getCurrentLocaleDateTime($item->specialPrice->fromDateTime)); } //special price from (MM-DD-YYYY) } $toDate = (array) $item->specialPrice->toDateTime; if (isset($item->specialPrice->toDateTime) && $item->specialPrice->toDateTime != NULL) { if (!empty($toDate)) { $product->setSpecialToDate(Mage::helper('customimport')->getCurrentLocaleDateTime($item->specialPrice->toDateTime)); } //special price to (MM-DD-YYYY) } $product->setWeight((double) $item->weight); $product->setStatus($p_status); $product->setTaxClassId($p_taxclass); $product->setDescription((string) $item->longDescription); $product->setShortDescription((string) $item->shortDescription); $product->setMetaTitle((string) $item->pageTitle); $product->setMetaKeyword((string) $item->metaKeywords); $product->setMetaDescription((string) $item->metaDescription); $product->setExternalImage((string) $item->originalImageUrl); $product->setExternalSmallImage((string) $item->largeImageUrl); $product->setExternalThumbnail((string) $item->smallImageUrl); $product->setShipmentType(0); //shipment type (0 - together, 1 - separately try { Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); $product->save(); $stockItem = Mage::getModel('cataloginventory/stock_item'); $stockItem->assignProduct($product); $stockItem->setData('stock_id', (int) 1); $stockItem->setData('use_config_manage_stock', (int) 1); $stockItem->setData('min_qty', (int) 0); $stockItem->setData('is_decimal_divided', (int) 0); $stockItem->setData('qty', (int) 0); $stockItem->setData('use_config_min_qty', 1); $stockItem->setData('use_config_backorders', 1); $stockItem->setData('min_sale_qty', 1); $stockItem->setData('use_config_min_sale_qty', 1); $stockItem->setData('use_config_max_sale_qty', 1); $stockItem->setData('is_in_stock', 1); $stockItem->setData('use_config_notify_stock_qty', 1); // Added Manage Stock Functionality // Manage Stock $inventory = $item->inventory; $manageItem = (string) strtoupper($inventory->manageStock); if ($manageItem == 'N') { $stockItem->setData('use_config_manage_stock', 0); $stockItem->setData('manage_stock', 0); } $stockItem->save(); $stockStatus = Mage::getModel('cataloginventory/stock_status'); $stockStatus->assignProduct($product); $stockStatus->saveProductStatus($product->getId(), 1); } catch (Exception $e) { $this->customHelper->reportError($e->getMessage()); $this->customHelper->sendLogEmail($this->logPath); } } else { $this->customHelper->reportError($this->customHelper->__('Attribute set ID # %s is missing. Hence skipped product # %s', $asid, $item->id)); } }
/** * After Save Attribute manipulation * * @param Mage_Catalog_Model_Product $object * @return Mage_Catalog_Model_Product_Attribute_Backend_Groupprice_Abstract */ public function afterSave($object) { $websiteId = Mage::app()->getStore($object->getStoreId())->getWebsiteId(); $isGlobal = $this->getAttribute()->isScopeGlobal() || $websiteId == 0; $groupRows = $object->getData($this->getAttribute()->getName()); if (empty($groupRows)) { $this->_getResource()->deleteGroupData($object->getId()); return $this; } $old = array(); $new = array(); $origGroupRows = $object->getOrigData($this->getAttribute()->getName()); if (!is_array($origGroupRows)) { $origGroupRows = array(); } foreach ($origGroupRows as $data) { if ($data['website_id'] > 0 || $data['website_id'] == '0' && $isGlobal) { $key = join('-', array_merge(array($data['website_id'], $data['cust_group']), $this->_getAdditionalUniqueFields($data))); $old[$key] = $data; } } // prepare data for save foreach ($groupRows as $data) { $hasEmptyData = false; foreach ($this->_getAdditionalUniqueFields($data) as $field) { if (empty($field)) { $hasEmptyData = true; break; } } if ($hasEmptyData || !isset($data['cust_group']) || !empty($data['delete'])) { continue; } if ($this->getAttribute()->isScopeGlobal() && $data['website_id'] > 0) { continue; } if (!$isGlobal && (int) $data['website_id'] == 0) { continue; } if (!isset($data['website_id'])) { $data['website_id'] = 0; } $key = join('-', array_merge(array($data['website_id'], $data['cust_group']), $this->_getAdditionalUniqueFields($data))); $useForAllGroups = $data['cust_group'] == Mage_Customer_Model_Group::CUST_GROUP_ALL; $customerGroupId = !$useForAllGroups ? $data['cust_group'] : 0; $new[$key] = array_merge(array('website_id' => $data['website_id'], 'all_groups' => $useForAllGroups ? 1 : 0, 'customer_group_id' => $customerGroupId, 'value' => $data['value']), $this->_getAdditionalUniqueFields($data)); } $delete = array_diff_key($old, $new); $insert = array_diff_key($new, $old); $update = array_intersect_key($new, $old); $isChanged = false; $productId = $object->getId(); if (!empty($delete)) { foreach ($delete as $data) { $this->_getResource()->deleteGroupData($productId, null, $data['group_id']); $isChanged = true; } } if (!empty($insert)) { foreach ($insert as $data) { $group = new Varien_Object($data); $group->setEntityId($productId); $this->_getResource()->saveGroupData($group); $isChanged = true; } } if (!empty($update)) { foreach ($update as $k => $v) { if ($old[$k]['value'] != $v['value']) { $group = new Varien_Object(array('value_id' => $old[$k]['value_id'], 'value' => $v['value'])); $this->_getResource()->saveGroupData($group); $isChanged = true; } } } if ($isChanged) { $valueChangedKey = $this->getAttribute()->getName() . '_changed'; $object->setData($valueChangedKey, 1); } /*$websiteId = Mage::app()->getStore($object->getStoreId())->getWebsiteId(); $isGlobal = $this->getAttribute()->isScopeGlobal() || $websiteId == 0; $priceRows = $object->getData($this->getAttribute()->getName()); if (empty($priceRows)) { if ($isGlobal) { $this->_getResource()->deletePriceData($object->getId()); } else { $this->_getResource()->deletePriceData($object->getId(), $websiteId); } return $this; } $old = array(); $new = array(); // prepare original data for compare $origGroupPrices = $object->getOrigData($this->getAttribute()->getName()); if (!is_array($origGroupPrices)) { $origGroupPrices = array(); } foreach ($origGroupPrices as $data) { if ($data['website_id'] > 0 || ($data['website_id'] == '0' && $isGlobal)) { $key = join('-', array_merge( array($data['website_id'], $data['cust_group']), $this->_getAdditionalUniqueFields($data) )); $old[$key] = $data; } } // prepare data for save foreach ($priceRows as $data) { $hasEmptyData = false; foreach ($this->_getAdditionalUniqueFields($data) as $field) { if (empty($field)) { $hasEmptyData = true; break; } } if ($hasEmptyData || !isset($data['cust_group']) || !empty($data['delete'])) { continue; } if ($this->getAttribute()->isScopeGlobal() && $data['website_id'] > 0) { continue; } if (!$isGlobal && (int)$data['website_id'] == 0) { continue; } $key = join('-', array_merge( array($data['website_id'], $data['cust_group']), $this->_getAdditionalUniqueFields($data) )); $useForAllGroups = $data['cust_group'] == Mage_Customer_Model_Group::CUST_GROUP_ALL; $customerGroupId = !$useForAllGroups ? $data['cust_group'] : 0; $new[$key] = array_merge(array( 'website_id' => $data['website_id'], 'all_groups' => $useForAllGroups ? 1 : 0, 'customer_group_id' => $customerGroupId, 'value' => $data['price'], ), $this->_getAdditionalUniqueFields($data)); } $delete = array_diff_key($old, $new); $insert = array_diff_key($new, $old); $update = array_intersect_key($new, $old); $isChanged = false; $productId = $object->getId(); if (!empty($delete)) { foreach ($delete as $data) { $this->_getResource()->deletePriceData($productId, null, $data['price_id']); $isChanged = true; } } if (!empty($insert)) { foreach ($insert as $data) { $price = new Varien_Object($data); $price->setEntityId($productId); $this->_getResource()->savePriceData($price); $isChanged = true; } } if (!empty($update)) { foreach ($update as $k => $v) { if ($old[$k]['price'] != $v['value']) { $price = new Varien_Object(array( 'value_id' => $old[$k]['price_id'], 'value' => $v['value'] )); $this->_getResource()->savePriceData($price); $isChanged = true; } } } if ($isChanged) { $valueChangedKey = $this->getAttribute()->getName() . '_changed'; $object->setData($valueChangedKey, 1); }*/ return $this; }
public function addProduct() { echo date("\nY-d-m H:i:s\n"); //$this->query("TRUNCATE TABLE `cataloginventory_stock_status_idx`"); $processes = Mage::getSingleton('index/indexer')->getProcessesCollection(); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL)); $processes->walk('save'); $connection = Mage::getModel('core/resource')->getConnection('core_read'); //$product = Mage::getModel('catalog/product'); $product = new Mage_Catalog_Model_Product(); // get data array $select = $connection->select()->from('oberig_products'); $result = $connection->query($select)->fetchAll(); //(PDO::FETCH_ASSOC); //mage::d($row); //echo $select->__toString();//die;//mage::D($result); //category mapping $result2 = array(); foreach ($result as &$row) { if (empty($row['category_ids'])) { $row['category_ids'] = array(); $result2[] = $row; continue; } $cats = explode(',', $row['category_ids']); foreach ($cats as &$cat) { $select = $connection->select()->from('oberig_category_mapping', 'new_cat_id')->where('old_cat_id=?', $cat); $res = $connection->query($select)->fetch(); $cat = $res['new_cat_id']; } $row['category_ids'] = $cats; $result2[] = $row; } $result = $result2; foreach ($result as $row) { //mage::d($row['category_ids']); $product = new Mage_Catalog_Model_Product(); // Build the product $product->setSku($row['sku']); $product->setAttributeSetId('4'); # 9 is for default $product->setTypeId('simple'); $product->setStatus(1); $product->setWebsiteIDs(array(1)); $product->setCategoryIds($row['category_ids']); $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); $product->setPrice($row['price']); $product->setData('store', $row['store']); //$product->setData('websites', $row['websites']); $product->setData('attribute_set', $row['attribute_set']); $product->setData('type', $row['type']); $product->setData('sku', $row['sku']); $product->setData('has_options', $row['has_options']); $product->setData('name', $row['name']); $product->setData('meta_title', $row['meta_title']); $product->setData('meta_description', $row['meta_description']); $product->setData('url_key', $row['url_key']); $product->setData('url_path', $row['url_path']); $product->setData('options_container', $row['options_container']); $product->setData('extra_title', $row['extra_title']); $product->setData('frame_gender', $row['frame_gender']); $product->setData('frame_shape', $row['frame_shape']); $product->setData('cost', $row['cost']); $product->setData('weight', $row['weight']); $product->setData('manufacturer', $row['manufacturer']); //$product->setData('status', $row['status']); $product->setData('tax_class_id', $row['tax_class_id']); //$product->setData('visibility', $row['visibility']); $product->setData('enable_googlecheckout', $row['enable_googlecheckout']); $product->setData('is_imported', $row['is_imported']); $product->setData('frame_type', $row['frame_type']); //$product->setData('sell_by_phone_only', $row['sell_by_phone_only']); $product->setData('description', $row['description']); $product->setData('short_description', $row['short_description']); $product->setData('meta_keyword', $row['meta_keyword']); $product->setData('special_from_date', $row['special_from_date']); $product->setData('min_qty', $row['min_qty']); $product->setData('use_config_min_qty', $row['use_config_min_qty']); $product->setData('is_qty_decimal', $row['is_qty_decimal']); $product->setData('backorders', $row['backorders']); $product->setData('use_config_backorders', $row['use_config_backorders']); $product->setData('min_sale_qty', $row['min_sale_qty']); $product->setData('use_config_min_sale_qty', $row['use_config_min_sale_qty']); $product->setData('max_sale_qty', $row['max_sale_qty']); $product->setData('use_config_max_sale_qty', $row['use_config_max_sale_qty']); $product->setData('low_stock_date', $row['low_stock_date']); $product->setData('notify_stock_qty', $row['notify_stock_qty']); $product->setData('use_config_notify_stock_qty', $row['use_config_notify_stock_qty']); $product->setData('manage_stock', $row['manage_stock']); $product->setData('use_config_manage_stock', $row['use_config_manage_stock']); $product->setData('stock_status_changed_automatically', $row['stock_status_changed_automatically']); $product->setData('use_config_qty_increments', $row['use_config_qty_increments']); $product->setData('qty_increments', $row['qty_increments']); $product->setData('use_config_enable_qty_increments', $row['use_config_enable_qty_increments']); $product->setData('enable_qty_increments', $row['enable_qty_increments']); $product->setData('product_name', $row['product_name']); $product->setData('store_id', $row['store_id']); $product->setData('product_type_id', $row['product_type_id']); $product->setData('product_status_changed', $row['product_status_changed']); $product->setData('product_changed_websites', $row['product_changed_websites']); $product->setData('custom_design', $row['custom_design']); $product->setData('page_layout', $row['page_layout']); $product->setData('image_label', $row['image_label']); $product->setData('small_image_label', $row['small_image_label']); $product->setData('thumbnail_label', $row['thumbnail_label']); $product->setData('gift_message_available', $row['gift_message_available']); $product->setData('framecolour', $row['framecolour']); $product->setData('special_price', $row['special_price']); $product->setData('is_recurring', $row['is_recurring']); $product->setData('frame_size', $row['frame_size']); $product->setData('custom_layout_update', $row['custom_layout_update']); $product->setData('special_to_date', $row['special_to_date']); $product->setData('news_from_date', $row['news_from_date']); $product->setData('news_to_date', $row['news_to_date']); $product->setData('custom_design_from', $row['custom_design_from']); $product->setData('custom_design_to', $row['custom_design_to']); $product->setData('stock_clearance', $row['stock_clearance']); $product->setData('lenstint', $row['lenstint']); $product->setData('framesizetest', $row['framesizetest']); $product->setStockData(array('is_in_stock' => $row['is_in_stock'], 'qty' => $row['qty'])); $product->setIsMassupdate(false); try { $product->save(); //Mage::getResourceSingleton('catalog/product_indexer_price')->reindexProductIds(array($productId)); //Mage::register('current_product', $product); //$product = null; } catch (Exception $ex) { echo 'test\\n'; echo $ex->getMessage(); //Handle the error } } $processes->walk('reindexAll'); $processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME)); $processes->walk('save'); $indexProcess = Mage::getSingleton('index/indexer')->getProcessByCode('catalog_product_price'); if ($indexProcess) { $indexProcess->reindexAll(); } echo date("\nY-d-m H:i:s\n"); }