Magento : Display html element based on product attribute set? - magento

I wish to display a static block on the product page if the product belongs to a certain Attribute Set
For example if I was a fashion store, and I have an attribute set of "Footwear" I only want the static block to show on product pages when the attribute set matches "Footwear"
I have found a little bit of code that outputs the ID of the Attribute set but I want to turn it into an else if statement.
<?php
$entityTypeId = Mage::getModel('eav/entity')
->setType('catalog_product')
->getTypeId();
$attributeSetName = 'Footwear';
$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->getCollection()
->setEntityTypeFilter($entityTypeId)
->addFieldToFilter('attribute_set_name', $attributeSetName)
->getFirstItem()
->getAttributeSetId();
echo $attributeSetId;
?>
Anyone have any ideas?
G

Add this method to the Product View Block
(not to core file app/code/core/Mage/Catalog/Block/Product/View.php of course):
public function checkAttributeSet($product = null, $attributeSetName = null)
{
if(is_null($product) || is_null($attributeSetName))
return false;
$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
$attributeSetModel->load($product->getAttributeSetId());
if($attributeSetModel->getAttributeSetName() == $attributeSetName) {
return true;
} else {
return false;
}
}
Then in app/design/frontend/package/theme/template/catalog/product/view.phtml:
if($this->checkAttributeSet($_product, 'Monitors')):
echo $this->getLayout()->createBlock('cms/block')->setBlockId('monitor')->toHtml();
elseif($this->checkAttributeSet($_product, 'Footwear')):
echo $this->getLayout()->createBlock('cms/block')->setBlockId('footwear')->toHtml();
endif;

FOR THE ADMINS WHO DELETE USEFUL INFORMATION FOR POINTS ON STACKOVERFLOW >>>> 3rd time replying to this post with updated material ya know just incase someone stumbles on this thread.
This is the updated magento 2.3 way of completing this task.
Add code to
module-catalog/view/frontend/templates/product/view
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$attributeSet = $objectManager->create('Magento\Eav\Api\AttributeSetRepositoryInterface');
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($_product->getId());
$attributeSetRepository = $attributeSet->get($product->getAttributeSetId());
$attribute_set_name = $attributeSetRepository->getAttributeSetName();
//$attribute_set_name_arr[] = $attribute_set_name;
//echo '<pre>'; print_r($attribute_set_name);
if( !empty($attribute_set_name) && $attribute_set_name == 'Rc' ) {
// echo $this->getLayout()
->createBlock('Magento\Cms\Block\Block')
->setBlockId('rcitems')
->toHtml();
}
?>
setBlockId = The Identifier of the block in admin.
Rc = is the attribute set
no need to add to default.xml

Related

Import Profile Product Review import/export

I'm using Magento extension https://www.magentocommerce.com/magento-connect/product-review-import-export.html for importing prodcuts review.
I've exported review from one Magento site and I'm trying to import on another website.
While importing products it's show message "Processed 0% 0/1 records" and keep it showing, No process in importing products.
Importing Preview
I've changed my table prefix in "app/code/local/MK/Reviewexport/Model/Convert/Adapter/Reviewimport.php" but still nothing happening.
Waited too long but it keep showing me "Processed 0% 0/1 records" I've too many reviews and so it was not working I've removed all reviews from CSV and kept only one review.
This extension is created by : https://magento.stackexchange.com/users/599/mufaddal
Anyways I've resolved the issue by making custom script for importing reviews which is exported by that mentioned extension.
Here is a code
<?php
ini_set('memory_limit', '128M');
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'app/Mage.php';
Mage::app();
$fileLocation = "var/import/import_review.csv";
$fp = fopen($fileLocation, 'r');
$count = 1;
while($data = fgetcsv($fp)){
if($count > 1){
//intiate requirement varibles
$_createdAt = $data[0];
$_sku = $data[1];
$_catalog = Mage::getModel('catalog/product');
$_productId = $_catalog->getIdBySku($_sku);
$_statusId = $data[2];
$_title = $data[3];
$_detail = $data[4];
$_customerId = NULL;
$_nickname = $data[5];
//load magento review model and assign values
$review = Mage::getModel('review/review');
$review->setCreatedAt($_createdAt); //created date and time
$review->setEntityPkValue($_productId);//product id
$review->setStatusId($_statusId); // status id
$review->setTitle($_title); // review title
$review->setDetail($_detail); // review detail
$review->setEntityId(1); // leave it 1
$review->setStoreId(Mage::app()->getStore()->getId()); // store id
$review->setCustomerId($_customerId); //null is for administrator
$review->setNickname($_nickname); //customer nickname
$review->setReviewId($review->getId());//set current review id
$review->setStores(array(Mage::app()->getStore()->getId()));//store id's
$review->save();
$review->aggregate();
//set review ratings
if($data[7]){
$arr_data = explode("#",$data[7]);
if(!empty($arr_data)) {
foreach($arr_data as $each_data) {
$arr_rating = explode(":",$each_data);
if($arr_rating[1] != 0) {
Mage::getModel('rating/rating')
->setRatingId($arr_rating[0])
->setReviewId($review->getId())
->setCustomerId($_customerId)
->addOptionVote($arr_rating[1], $_productId);
}
}
}
$review->aggregate();
}
}
// if($count == 5){
// die("total $count reviews are imported!");
// }
$count++;
}
echo "total $count reviews are imported!";
?>

How to create in Magento with custom code?

I am using this code to create categories and subcategories. This code works fine but the problem is I can't create my own category codes. And I need it to use it for the requeriments.
$category = Mage::getModel('catalog/category');
$category->setStoreId(0); // 0 = default/all store view. If you want to save data for a specific store view, replace 0 by Mage::app()->getStore()->getId().
//if update
if ($id) {
$category->load($id);
}
$general['name'] = "My Category";
$general['path'] = "1/3/"; // catalog path here you can add your own ID
$general['description'] = "Great My Category";
$general['meta_title'] = "My Category"; //Page title
$general['meta_keywords'] = "My , Category";
$general['meta_description'] = "Some description to be found by meta search robots. 2";
$general['landing_page'] = ""; //has to be created in advance, here comes id
$general['display_mode'] = "PRODUCTS"; //static block and the products are shown on the page
$general['is_active'] = 1;
$general['is_anchor'] = 0;
$general['page_layout'] = 'two_columns_left';
//$general['url_key'] = "cars";//url to be used for this category's page by magento.
//$general['image'] = "cars.jpg";
$category->addData($general);
try {
$category->setId(255); // Here you cant set your own entity id
$category->save();
echo "Success! Id: ".$category->getId();
}
catch (Exception $e){
echo $e->getMessage();
}
I tried to do something like that:
$general['id'] = $myCustomId;
But it's not working.
The key needs to map the column header, which is entity_id. So, change $general['id'] to
$general['entity_id'] = $myCustomId;

Magento re-generate url-keys for categories

I must re-generate all url-keys for all categories.
When I added some main categories i copied them using one of way from forum.
Everything was going ok, but when i’m copied about 20k categories i saw: when the name has polish letter the rest was cutted:
Example:
name of category: Części karoseryjne
should be: czesci-karoseryjne
after copy: cz
name of category: Próg zwalniajacy
should be: prog-zwalniajacy
after copy: pr
I’m found on polish forum the way to fix it (with polish letters), but it works only with new added categories.
Now, when i select any category, clear the url-key and click save - the naming is ok, but ....... there is 20k categories…
Can somebody write how to fix it ?
http://www.errorin.com/open-source/how-to-add-category-programmatically-in-magento-1-7-0-with-custom-field/
require_once 'app/Mage.php';
Mage::app('default'); // Default or your store view name.
//get a new category object
$category = Mage::getModel('catalog/category');
$category->setStoreId(0); // 0 = default/all store view. If you want to save data for a specific store view, replace 0 by Mage::app()->getStore()->getId().
//if update
if ($id) {
$category->load($id);
}
$general['name'] = "My Category";
$general['path'] = "1/2/23"; // catalog path
$general['description'] = "Great My Category";
$general['meta_title'] = "My Category"; //Page title
$general['meta_keywords'] = "My , Category";
$general['meta_description'] = "Some description to be found by meta search robots. 2";
$general['landing_page'] = ""; //has to be created in advance, here comes id
$general['display_mode'] = "PRODUCTS_AND_PAGE"; //static block and the products are shown on the page
$general['is_active'] = 1;
$general['is_anchor'] = 0;
$general['page_layout'] = 'two_columns_left';
//$general['url_key'] = "cars";//url to be used for this category's page by magento.
//$general['image'] = "cars.jpg";
$category->addData($general);
try {
$category->save();
echo "Success! Id: ".$category->getId();
}
catch (Exception $e){
echo $e->getMessage();
}

Programmatically create auto generated coupon codes in Magento?

Based on other stackoverflow posts, I've been able to use the following code to programmatically generate individual shopping cart price rule coupons in Magento.
How can I programmatically call the "Auto Generate Coupon" feature to create 100 unique coupons for each price rule I make? Thanks!
$coupon = Mage::getModel('salesrule/rule');
$coupon->setName($_coupon['name'])
->setDescription('this is a description')
->setFromDate(date('Y-m-d'))
->setCouponType(2)
->setCouponCode($_coupon['code'])
->setUsesPerCoupon(1000)
->setUsesPerCustomer(100)
->setCustomerGroupIds(array(1)) //an array of customer groupids
->setIsActive(1)
//serialized conditions. the following examples are empty
->setConditionsSerialized('a:6:{s:4:"type";s:32:"salesrule/rule_condition_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
->setActionsSerialized('a:6:{s:4:"type";s:40:"salesrule/rule_condition_product_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
->setStopRulesProcessing(0)
->setIsAdvanced(1)
->setProductIds('')
->setSortOrder(0)
->setSimpleAction('by_percent')
->setDiscountAmount(100)
->setDiscountQty(null)
->setDiscountStep('0')
->setSimpleFreeShipping('0')
->setApplyToShipping('0')
->setIsRss(0)
->setWebsiteIds(array(1));
$coupon->save();
For instance, this one price rule might have a whole list of Auto-Generated Coupon Codes (htgf-7774, htgf-2345, etc) using the function that is available when manually creating price rules in the admin panel.
EDIT:
I've gotten closer, using the following code. Still don't know how to specifically assign the auto generation pattern
->setName('Name')
->setDescription('this is a description')
->setFromDate('2013-03-06')
->setToDate(NULL)
->setUsesPerCustomer('100')
->setIsActive('1')
->setConditionsSerialized('a:6:{s:4:"type";s:32:"salesrule/rule_condition_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
->setActionsSerialized('a:6:{s:4:"type";s:40:"salesrule/rule_condition_product_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
->setStopRulesProcessing('0')
->setIsAdvanced('1')
->setProductIds(NULL)
->setSortOrder('0')
->setSimpleAction('by_percent')
->setDiscountAmount('100.0000')
->setDiscountQty(NULL)
->setDiscountStep('0')
->setSimpleFreeShipping('0')
->setApplyToShipping('0')
->setTimesUsed('1')
->setIsRss('0')
->setCouponType('2')
->setUseAutoGeneration('1')
->setUsesPerCoupon('1000')
->setCustomerGroupIds(array('1',))
->setWebsiteIds(array('1',))
->setCouponCode(NULL)
Thanks to a nifty post I found while googling this (http://fragmentedthought.com/fragments/programatically-creating-sales-rule-coupon-code), I answered my own question:
// Get the rule in question
$rule = Mage::getModel('salesrule/rule')->load(21); //21 = ID of coupon in question
// Define a coupon code generator model instance
// Look at Mage_SalesRule_Model_Coupon_Massgenerator for options
$generator = Mage::getModel('salesrule/coupon_massgenerator');
$parameters = array(
'count'=>5,
'format'=>'alphanumeric',
'dash_every_x_characters'=>4,
'prefix'=>'ABCD-EFGH-',
'suffix'=>'-WXYZ',
'length'=>8
);
if( !empty($parameters['format']) ){
switch( strtolower($parameters['format']) ){
case 'alphanumeric':
case 'alphanum':
$generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC );
break;
case 'alphabetical':
case 'alpha':
$generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHABETICAL );
break;
case 'numeric':
case 'num':
$generator->setFormat( Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_NUMERIC );
break;
}
}
$generator->setDash( !empty($parameters['dash_every_x_characters'])? (int) $parameters['dash_every_x_characters'] : 0);
$generator->setLength( !empty($parameters['length'])? (int) $parameters['length'] : 6);
$generator->setPrefix( !empty($parameters['prefix'])? $parameters['prefix'] : '');
$generator->setSuffix( !empty($parameters['suffix'])? $parameters['suffix'] : '');
// Set the generator, and coupon type so it's able to generate
$rule->setCouponCodeGenerator($generator);
$rule->setCouponType( Mage_SalesRule_Model_Rule::COUPON_TYPE_AUTO );
// Get as many coupons as you required
$count = !empty($parameters['count'])? (int) $parameters['count'] : 1;
$codes = array();
for( $i = 0; $i < $count; $i++ ){
$coupon = $rule->acquireCoupon();
$code = $coupon->getCode();
$codes[] = $code;
}
return $codes;
This successfully generated the following codes:
ABCD-EFGH-ZC6V-ZJWD-WXYZ
ABCD-EFGH-4XMX-353L-WXYZ
ABCD-EFGH-XCJB-5GQI-WXYZ
ABCD-EFGH-UEAO-L1NJ-WXYZ
ABCD-EFGH-59B3-50T2-WXYZ

Magento: get max and min price for bundle product

I tried several ideas I could find at google, but no one did work for me for few days. Finally I found a way to display in a custom extension the "minimal possible price" and the "maximal possible price" for a bundle product in magento:
$_product_id = YOUR_BUNDLE_PRODUCT_ID;
// highest possible price for this bundle product
$return_type = 'max'; // because I used this in a helper method
// lowest possible price for this bundle product
// $return_type = 'min';
$model_catalog_product = Mage::getModel('catalog/product'); // getting product model
$_product = $model_catalog_product->load( $_product_id );
$TypeInstance = $_product->getTypeInstance(true);
$Selections = $TypeInstance->getSelectionsCollection($OptionIds, $_product );
$Options = $TypeInstance->getOptionsByIds($OptionIds, $_product);
$bundleOptions = $Options->appendSelections($Selections, true);
$minmax_pricevalue = 0; // to sum them up from 0
foreach ($bundleOptions as $bundleOption) {
if ($bundleOption->getSelections()) {
$bundleSelections = $bundleOption->getSelections();
$pricevalues_array = array();
foreach ($bundleSelections as $bundleSelection) {
$pricevalues_array[] = $bundleSelection->getPrice();
}
if ( $return_type == 'max' ) {
rsort($pricevalues_array); // high to low
} else {
sort($pricevalues_array); // low to high
}
// sum up the highest possible or lowest possible price
$minmax_pricevalue += $pricevalues_array[0];
}
}
// echo $minmax_pricevalue;
echo ''.Mage::helper('core')->currency($minmax_pricevalue, true, false).'';
If you have better and shorter ways feel free to post here. Thanks to all involved!
Background of all was that, I have made a custom extension and wanted also to show there the "minimal possible price" and the "maximal possible price" for such a configuration. Magento-Setup was: Native "bundle product" several "Bundle Items Options" connected my "bundle product". Each "bundle option" has multiple simple products with different prices in it. I think that was the point here.
Hope that all helps someone - love to share such stuff :-)
Magento has build in function for that purpose:
Mage::getModel('bundle/product_price')->getTotalPrices($_product,'min',1);
Here once again the final working code:
$_product_id = YOUR_BUNDLE_PRODUCT_ID;
// highest possible price for this bundle product
$return_type = 'max'; // because I used this in a helper method
// lowest possible price for this bundle product
// $return_type = 'min';
$model_catalog_product = Mage::getModel('catalog/product'); // getting product model
$_product = $model_catalog_product->load( $_product_id );
$TypeInstance = $_product->getTypeInstance(true);
$Selections = $TypeInstance->getSelectionsCollection($OptionIds, $_product );
$Options = $TypeInstance->getOptionsByIds($OptionIds, $_product);
$bundleOptions = $Options->appendSelections($Selections, true);
$minmax_pricevalue = 0; // to sum them up from 0
foreach ($bundleOptions as $bundleOption) {
if ($bundleOption->getSelections()) {
$bundleSelections = $bundleOption->getSelections();
$pricevalues_array = array();
foreach ($bundleSelections as $bundleSelection) {
$pricevalues_array[] = $bundleSelection->getPrice();
}
if ( $return_type == 'max' ) {
rsort($pricevalues_array); // high to low
} else {
sort($pricevalues_array); // low to high
}
// sum up the highest possible or lowest possible price
$minmax_pricevalue += $pricevalues_array[0];
}
}
// echo $minmax_pricevalue;
echo ''.Mage::helper('core')->currency($minmax_pricevalue, true, false).'';
I had a similar problem a while back and came up with this (with some help from Inchoo's blog for getting the bundled product collection). It loads all of the bundled products associated with the main product_id into an array. By sorting the array you get the min on the bottom and max at the end which I retrieved with $bundled_prices[0] and array_slice($bundled_prices, -1, 1, false).
$product_id = YOUR_PRODUCT_ID;
$bundled_product = new Mage_Catalog_Model_Product();
$bundled_product->load($product_id);
$selectionCollection = $bundled_product->getTypeInstance(true)->getSelectionsCollection(
$bundled_product->getTypeInstance(true)->getOptionsIds($bundled_product), $bundled_product
);
$bundled_items = array();
foreach($selectionCollection as $option) {
if ($option->getPrice()!="0.0000"){
$bundled_prices[]=$option->getPrice();
}
}
sort($bundled_prices);
$min_price=$bundled_prices[0];
$max_price_tmp=array_slice($bundled_prices, -1, 1, false);
$max_price=$max_price_tmp[0];
echo "Min: " . $min_price . '<br>';
echo "Max: " . $max_price;

Resources