how to import discount coupon csv file in magento admin - magento

I have a csv of coupon codes, i want to import it in magento.
please help me to how import it.
i have a script but its not working:-
<?php
$mageFilename = '/opt/bitnami/apps/magento/htdocs/app/Mage.php';
require_once $mageFilename;
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('default');
Mage::register('isSecureArea', 1);
function getAllWbsites(){
//get all wabsites
$websites = Mage::getModel('core/website')->getCollection();
$websiteIds = array();
foreach ($websites as $website){
$websiteIds[] = $website->getId();
}
return $websiteIds;
}
//read comments for each line
function generateRule($rulename, $desc, $status, $customerGroups, $couponCode, $fromDate, $toDate, $discountType, $discountAmount){
$couponCheck = Mage::getModel('salesrule/rule')->getCollection()
->addFieldToFilter('code',$couponCode)
->load();
$couponCheckArr = $couponCheck->getData();
if(count($couponCheckArr)>0) {
return false;
}
$rule = Mage::getModel('salesrule/rule');
$rule->setName($rulename);
$rule->setDescription($desc);
$rule->setFromDate($fromDate);//starting today
if($toDate!="") {
$rule->setToDate($toDate);//if you need an expiration date
}
$rule->setCouponCode($couponCode);
$rule->setUsesPerCoupon(1);//number of allowed uses for this coupon
$rule->setUsesPerCustomer(1);//number of allowed uses for this coupon for each customer
$customerGroups = explode(',',$customerGroups);
$rule->setCustomerGroupIds($customerGroups);//if you want only certain groups replace getAllCustomerGroups() with an array of desired ids
$rule->setIsActive($status);
$rule->setStopRulesProcessing(0);//set to 1 if you want all other rules after this to not be processed
$rule->setIsRss(0);//set to 1 if you want this rule to be public in rss
$rule->setIsAdvanced(1);//have no idea what it means :)
$rule->setProductIds('');
$rule->setSortOrder(0);// order in which the rules will be applied
$rule->setSimpleAction($discountType);
//all available discount types
//by_percent - Percent of product price discount
//by_fixed - Fixed amount discount
//cart_fixed - Fixed amount discount for whole cart
//buy_x_get_y - Buy X get Y free (discount amount is Y)
$rule->setDiscountAmount($discountAmount);//the discount amount/percent. if SimpleAction is by_percent this value must be <= 100
$rule->setDiscountQty(0);//Maximum Qty Discount is Applied to
$rule->setDiscountStep(0);//used for buy_x_get_y; This is X
$rule->setSimpleFreeShipping(0);//set to 1 for Free shipping
$rule->setApplyToShipping(0);//set to 0 if you don't want the rule to be applied to shipping
$rule->setWebsiteIds(getAllWbsites());//if you want only certain websites replace getAllWbsites() with an array of desired ids
$conditions = array();
$conditions[1] = array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 1,
'new_child' => ''
);
$rule->setData('conditions',$conditions);
$rule->loadPost($rule->getData());
$rule->setCouponType(2);
if($rule->save()) {
return true;
}
else {
return false;
}
}
$fp = fopen('coupons-feed.csv','r') or die("can't open file");
$count = 0;
$countNotImpt = 0;
$i = 0;
while($csv_line = fgetcsv($fp,1024,"\t")) {
if($i>0) {
$OneTime = $csv_line[0];
$Name = $csv_line[1];
$AlternateCode = $csv_line[2];
$DiscountType = $csv_line[3];
$MinCartValue = $csv_line[4];
$ProductsAssigned = $csv_line[5];
$Limitedtoone = $csv_line[6];
$ExcludeProducts = $csv_line[7];
$ExpirationDate = $csv_line[8];
$DateCreated = $csv_line[9];
if(generateRule($OneTime,$Name,$AlternateCode,$DiscountType,$MinCartValue,$ProductsAssigned,$Limitedtoone,$ExcludeProducts $ExpirationDate,$DateCreated )) {
$count++;
}
else{
$countNotImpt++;
}
}
$i++;
}
fclose($fp) or die("can't close file");
echo $count.' coupon successfully added.<br>';
echo $countNotImpt.' coupon already exits.<br>';
?>
i upload this script and csv on root . but its not working. please tell me about this beacause i am new in magento.

#Brar Kirmal, you can try the below script, I created this script for one of my project you can try in your project.
$mageFilename = 'Mage.php'; // it may different as per the location of this file
require_once $mageFilename;
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('default');
Mage::register('isSecureArea', 1);
function getAllWbsites(){
//get all wabsites
$websites = Mage::getModel('core/website')->getCollection();
$websiteIds = array();
foreach ($websites as $website){
$websiteIds[] = $website->getId();
}
return $websiteIds;
}
//read comments for each line
function generateRule($rulename, $desc, $status, $customerGroups, $couponCode, $fromDate, $toDate, $discountType, $discountAmount){
$couponCheck = Mage::getModel('salesrule/rule')->getCollection()
->addFieldToFilter('code',$couponCode)
->load();
$couponCheckArr = $couponCheck->getData();
if(count($couponCheckArr)>0) {
return false;
}
$rule = Mage::getModel('salesrule/rule');
$rule->setName($rulename);
$rule->setDescription($desc);
$rule->setFromDate($fromDate);//starting today
if($toDate!="") {
$rule->setToDate($toDate);//if you need an expiration date
}
$rule->setCouponCode($couponCode);
$rule->setUsesPerCoupon(1);//number of allowed uses for this coupon
$rule->setUsesPerCustomer(1);//number of allowed uses for this coupon for each customer
$customerGroups = explode(',',$customerGroups);
$rule->setCustomerGroupIds($customerGroups);//if you want only certain groups replace getAllCustomerGroups() with an array of desired ids
$rule->setIsActive($status);
$rule->setStopRulesProcessing(0);//set to 1 if you want all other rules after this to not be processed
$rule->setIsRss(0);//set to 1 if you want this rule to be public in rss
$rule->setIsAdvanced(1);//have no idea what it means :)
$rule->setProductIds('');
$rule->setSortOrder(0);// order in which the rules will be applied
$rule->setSimpleAction($discountType);
//all available discount types
//by_percent - Percent of product price discount
//by_fixed - Fixed amount discount
//cart_fixed - Fixed amount discount for whole cart
//buy_x_get_y - Buy X get Y free (discount amount is Y)
$rule->setDiscountAmount($discountAmount);//the discount amount/percent. if SimpleAction is by_percent this value must be <= 100
$rule->setDiscountQty(0);//Maximum Qty Discount is Applied to
$rule->setDiscountStep(0);//used for buy_x_get_y; This is X
$rule->setSimpleFreeShipping(0);//set to 1 for Free shipping
$rule->setApplyToShipping(0);//set to 0 if you don't want the rule to be applied to shipping
$rule->setWebsiteIds(getAllWbsites());//if you want only certain websites replace getAllWbsites() with an array of desired ids
$conditions = array();
$conditions[1] = array(
'type' => 'salesrule/rule_condition_combine',
'aggregator' => 'all',
'value' => 1,
'new_child' => ''
);
$rule->setData('conditions',$conditions);
$rule->loadPost($rule->getData());
$rule->setCouponType(2);
if($rule->save()) {
return true;
}
else {
return false;
}
}
$fp = fopen('coupon.csv','r') or die("can't open file");// replace it with your file name and location
$count = 0;
$countNotImpt = 0;
$i = 0;
while($csv_line = fgetcsv($fp,1024,"\t")) {
if($i>0) {
$rulename = $csv_line[0];
$desc = $csv_line[1];
$status = $csv_line[2];
$customerGroups = $csv_line[3];
$couponCode = $csv_line[4];
$fromDate = $csv_line[5];
$toDate = $csv_line[6];
$discountType = $csv_line[7];
$discountAmount = $csv_line[8];
if(generateRule($rulename, $desc, $status, $customerGroups, $couponCode, $fromDate, $toDate, $discountType, $discountAmount)) {
$count++;
}
else{
$countNotImpt++;
}
}
$i++;
}
fclose($fp) or die("can't close file");
echo $count.' coupon successfully added.<br>';
echo $countNotImpt.' coupon already exits.<br>';

Related

Magento2 product import pragmatically i want skip images if not present on csv?

I am trying to upload product pragmatically through CSV all script run well but i have only 1 issue i have 3 column of images in my CSV 1st images are available but in 2nd and 3rd column some images are missing name are present but images are not found in directory but when i run script only one images are save rest of present images are not saved
My Code is
<?php
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$objectManager1 = Magento\Framework\App\ObjectManager::getInstance();
$directoryList = $objectManager1->get('\Magento\Framework\App\Filesystem\DirectoryList');
$path = $directoryList->getPath('media');
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$myarray = glob("test.csv");
usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
if(count($myarray)){
$csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
array_walk($csv_map, function(&$a) use ($csv_map) {
$a = array_combine($csv_map[0], $a);
});
array_shift($csv_map);
$message = '';
$count = 1;
foreach($csv_map as $data){
//echo '<pre>';print_r($data);exit;
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product->setName(trim($data['NAME']));
$product->setTypeId('simple');
$product->setAttributeSetId(4);
$product->setSku(trim($data['MODEL NUMBER']));
$product->setUrlPath(trim($data['url']).trim($data['MODEL NUMBER']).('zenith'));
$product->setWebsiteIds(array(1));
$product->setVisibility(4);
$product->setBrand(trim($data['BRAND']));
$product->setFunctions(trim($data['FUNCTIONS']));
$product->setPowerReserve(trim($data['POWER RESERVE']));
$product->setStrapType(trim($data['STRAP TYPE']));
$product->setWarranty(trim($data['WARRANTY']));
$product->setFamily(trim($data['FAMILY']));
$product->setWaterResistance(trim($data['WATER RESISTANCE']));
$product->setCreatedAt(strtotime('now'));
$product->setPrice(trim($data['PRICE']));
$product->setcaseSize(trim($data['CASE SIZE']));
//$product->setColor(trim($data['dial_colour']));
$product->setMovement(trim($data['MOVEMENT']));
$product->setCaseShape(trim($data['CASE SHAPE']));
//$product->setGender(trim($data['gender']));
$product->setCaseMaterial(trim($data['CASE MATERIAL']));
//$_product->setShortDescription(trim($data['Short Description'])); // add text attribute
//$_product->setDescription(trim($data['Long Description'])); // add text attribute
$img_url = trim($data['IMAGE1']);
$img_url1=trim($data['IMAGE2']);
$img_url2=trim($data['IMAGE3']);
$dir = $directoryList->getPath('media').'/big/';
$imgpath = $dir.$img_url;
$imgpath1 = $dir.$img_url1;
$imgpath2 = $dir.$img_url2;
$product->addImageToMediaGallery($imgpath, array('image'), false, false);
if (file_exists($dir.$img_url1)) {
$product->addImageToMediaGallery($imgpath1, array('thumbnail'), false, false);
}
if (file_exists($dir.$img_url2)) {
$product->addImageToMediaGallery($imgpath2, array('small_image'), false, false);
}
$product->setStockData(array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 100 //qty
)
);
$product->save();
}
echo'sucess';
}
?>
please suggest what i am doing wrong in image section
Check the image existence By
#exif_imagetype($image_path).
Thank you

Magento Checkout count weight of products which match attribute

I need to count how many products of a specific type are in the checkout. But only(!) the products which are of a specific type. The type is defined in a drop down attribute.
This is a code counting the weight and works perfectly.
\template\checkout\cart.phtml
<?php $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
$weight = 0;
foreach($items as $item) {
$weight += ($item->getWeight() * $item->getQty()) ;
}
echo $weight;
?>
But how to count only the products which have a specific attribute value?
Like
=> "count only products which have Attribute color = green"
I found lot about collection and filter but it seems not to work for the shopping cart items.
Hope you can help me.
You have to load the product model as you're looping ( Expensive ) and then you're able to call attributes on it like so:
foreach( $oItems as $oItem )
{
$oProduct = $oItem->getProduct();
$oProductModel = Mage::getModel( 'catalog/product' )->load( $oProduct->getId() );
// For code...
$sColor = $oProductModel->getData( 'color' );
var_dump( $sColor );
// For text...
$sFormat = $oProductModel->getAttributeText( 'color' );
var_dump( $sFormat );
}
This is how you can get the attribute value (after loading your product):
$product = $item->getProduct();
$value = $product->getAttributeText($yourAttributeCode);
But notice for this in order to work you need to set: 'Show in Product Listing' or 'Used in Product Listing' to yes in the attribute editor from admin panel.
And for the grouping part, one possible way could be doing something like this (it makes sense only if you have a small number of values for your specific attribute):
$weights = array ('redWeight' => 0, 'blueWeight' => 0, 'yellowWeight' => 0, ..);
$groupRed = array();
$groupGreen = array();
...
foreach($items as $item) {
$product = $item->getProduct();
$value = $product->getAttributeText('yourAttributeCode');
$weight = ($item->getWeight() * $item->getQty());
if($value){ //Do all products have this attribute?
Switch($value){
case "red":
$Weights['redWeight'] += $weight;
$groupRed[] = $item;
break;
case "green":
....
}
} else {
continue;
}
}
....
HERE YOU HAVE GROUPS OF YOUR ITEMS ACCORDING TO THEIR SPECIFIC ATTRIBUTE VALUES

How to create custom script for import products in magento

I am working on magento 1.8 version.
I need to create custom script or extenson for import product from my custom csv file which have some different fields.
Any help would be much appriciated.
Thanks
Best way is to use OS Magmi, is much more faster than script an is simple to configure and periodical run.
http://sourceforge.net/projects/magmi/
You can also create a script which can you run.
you need to get data from csv file to memory
2 convert them to array
3 list array for each product
4 in foreach loop save or update product.
Some basic script:
<?php
$max_i = 20000; // maximal ammount
chdir(dirname(__FILE__)); /
//error_reporting(E_ALL | E_STRICT);
//ini_set("display_errors", 1);
ini_set("memory_limit","1024M");
ini_set('max_execution_time', 3600000);
date_default_timezone_set('Europe/Prague');
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
//////// SKU from CSV
$csv = file_get_contents ('yourcsvfile.csv');
function parse_csv ($csv_string, $delimiter = ";", $skip_empty_lines = true, $trim_fields = true)
{
$enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
$enc = preg_replace_callback(
'/"(.*?)"/s',
function ($field) {
return urlencode(utf8_encode($field[1]));
},
$enc
);
$lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
return array_map(
function ($line) use ($delimiter, $trim_fields) {
$fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
return array_map(
function ($field) {
return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
},
$fields
);
},
$lines
);
}
// list to array
$vystup = parse_csv($csv);
$seznamsku = array();
foreach ($vystup as $sku) {
array_push($seznamsku, $sku[0]);
unset($seznamsku[0]);
$seznamskufin = array_filter($seznamsku, 'strlen');
};
require("../../app/Mage.php");
echo "START ".date('h:i:s')."\n\n";
Mage::init();
// Set an Admin Session
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(1);
$session = Mage::getSingleton('admin/session');
$session->setUser($userModel);
$session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
$pocet = 1;
foreach ($seznamskufin as $item) {
echo "\n number(".$pocet.")..sku(".$item.")..";
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$item);
if(is_object($product)) { //if is product exist in Magento
if (empty($product->getShortDescription())) { // if is value empty
$product->setShortDescription($ZboziDetail['info']); // write to magento
echo "..(importing)..";
}
else
{
echo "..(skipped).."; // exists
};
$product->save(); // save to magento
echo "..saved";
} else { echo ".(skiped)"; };
unset($item);
unset($product);
unset($ZboziDetail);
unset($product_imageUrl);
unset($newimage);
unset($e);
$pocet++;
};
$time_end = microtime_float();
$time = $time_end - $time_start;
echo " \n\n All done in ".$time." seconds.";
$logfile = fopen('log.txt', 'a');
fwrite($logfile, $seznamskufin);
fclose($logfile);
unset($response);
unset($vystup);
unset($seznamsku);
unset($seznamskufin);
?>
I think the easiest and safest way is to create a simple script (outside Magento) that transforms your csv to the csv structure used for import in System->Import/Export->Import.
TO see the format of the csv you need go to System->Import/Export->Export and export your current products.

How to get bundle product price in Magento?

I have an bundle product as array like this: (take from params when add product to cart)
Array
(
[product] => 165
[bundle_option] => Array
(
[17] => 47
[22] => 60
[16] => 46
[15] => 42
[14] => Array
(
[0] => 39
)
)
)
How could I get price for this bundle product?
Something like this should also work:
public function getDisplayPrice($product) {
if($product->getFinalPrice()) {
return $product->getFormatedPrice();
} else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
$optionCol= $product->getTypeInstance(true)
->getOptionsCollection($product);
$selectionCol= $product->getTypeInstance(true)
->getSelectionsCollection(
$product->getTypeInstance(true)->getOptionsIds($product),
$product
);
$optionCol->appendSelections($selectionCol);
$price = $product->getPrice();
foreach ($optionCol as $option) {
if($option->required) {
$selections = $option->getSelections();
$minPrice = min(array_map(function ($s) {
return $s->price;
}, $selections));
if($product->getSpecialPrice() > 0) {
$minPrice *= $product->getSpecialPrice()/100;
}
$price += round($minPrice,2);
}
}
return Mage::app()->getStore()->formatPrice($price);
} else {
return "";
}
}
You can use the built-in static method calculatePrice of Mage_Bundle_Model_Product_Price like so:
if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE){
$pricemodel = Mage::getModel('bundle/product_price');
$price = $pricemodel::calculatePrice(
$product->getData('price'),
$product->getSpecialPrice(),
$product->getSpecialPriceFrom(),
$product->getSpecialPriceTo(),
false,
Mage::app()->getStore()->getWebsite()->getId(),
Mage::getSingleton('customer/session')->getCustomer()->getGroupId(),
$product->getId()
);
$finalprice = $this->helper('core')->currencyByStore(Mage::helper('tax')->getPrice($product, $price));
}
You can use the getMinimalPrice() and getMaximalPrice() functions in the Mage_Bundle_Product_Price class, which are written specifically for bundle products.
// load product
$product = new Mage_Catalog_Model_Product();
$product->load(165);
$priceModel = $product->getPriceModel();
// get options
$block = Mage::getSingleton('core/layout')->createBlock('bundle/catalog_product_view_type_bundle');
$options = $block->setProduct($product)->getOptions();
$price = 0;
foreach ($options as $option) {
$selection = $option->getDefaultSelection();
if ($selection === null) {
continue;
}
$price += $priceModel->getSelectionPreFinalPrice($product, $selection, $selection->getSelectionQty());
}
or, you can use my magento module: https://github.com/head82/KH_ExtendedBundlePrice tested with magento 1.7
#Kevin, great work. I personally needed a slight modification. In Magento 1.7.0.2, the function getSelectionPreFinalPrice() actually calls upon getSelectionPrice() which calls upon getSelectionFinalTotalPrice() - but in that last part the price is calculated with the final price (so including tier-pricing and special prices) and not the original price.
I applied the following snippet to get that original price (without tier-pricing and without special prices):
$_normalPrice = 0;
$_options = $_priceModel->getOptions($_product);
foreach($_options as $_option) {
$_selection = $_option->getDefaultSelection();
if ($_selection === null) continue;
$_normalPrice = $_normalPrice + $_selection->getPrice();
}
Here is the magento way:
$_product = $this->getProduct();
$_priceModel = $_product->getPriceModel();
list($_minimalPriceTax, $_maximalPriceTax) = $_priceModel->getTotalPrices($_product, null, null, false);
list($_minimalPriceInclTax, $_maximalPriceInclTax) = $_priceModel->getTotalPrices($_product, null, true, false);
Assuming that $this->getProduct() returns Catalog/Product Model.
Works both with fixed and dynamic price types even compatible with Configurable Bundle extention. Taken from design/base/default/template/bundle/catalog/product/price.phtml
I solved it by own method, not sure its acceptable or not.send the post values and product id, the model will return the price.
$bundle_option = Mage::app ()->getRequest ()->getParam('bundle_option');
$bundle_option_array = call_user_func_array('array_merge', $bundle_option);
$price = Mage::Helper('airhotels/bundle')->getBundlePrice($productid,$bundle_option_array);
my helper file is
public function getBundlePrice($productId,$bundle_option_array) {
$product = new Mage_Catalog_Model_Product();
$product->load($productId);
$price=0;
$selectionCollection = $product->getTypeInstance(true)->getSelectionsCollection($product->getTypeInstance(true)->getOptionsIds($product), $product);
foreach($selectionCollection as $option)
{
if (in_array($option->getSelectionId(), $bundle_option_array)){
$price += $option->price;
}
}
return $price;
}
Concept: I built a 1-D array from the 2-D array(the question). from the function in helper we can get all the selection id of a bundle product . By matching (using in_array) we can calculate the price for our custom selected products.
Although I'm sure you have figured out what you needed several year ago I'm not quite sure where in the accepted answer you would put your params.
What I found was that you can get the price for a bundle product with getFinalPrice() just like any other product, but you can set the selected options using the catalog/product helper.
$_product = Mage::getModel('catalog/product')->load($this->getRequest()->getPost()['product'];
$productHelper = $this->helper('catalog/product');
//getpost() contains the array you mentioned when you click add to cart
$_configuredProducts = $_product->getTypeInstance(true)->processConfiguration(new Varien_Object($this->getRequest()->getPost()), $_product,Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_FULL );
echo $_product->getFinalPrice();

Magento - How can I add rating information to a review

I'm manually creating reviews in Magento and I'm trying to find out how I add the rating information in? I can add the reviews no problem but I'm struggling with the rating values (star values).
I have an array that looks like this:
array("Price"=>80, "Value"=>60, "Quality"=>60);
How can I add that to the star system and the Summary Rating?
Thanks.
Ok, so this is what I have so far:
This adds a review:
$review->setEntityPkValue(23);//product id
$review->setStatusId(1);
$review->setTitle("title");
$review->setDetail("detail");
$review->setEntityId($review->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE));
$review->setStoreId(Mage::app()->getStore()->getId());
$review->setStatusId(1); //approved
$review->setNickname("Me");
$review->setReviewId($review->getId());
$review->setStores(array(Mage::app()->getStore()->getId()));
$review->save();
$review->aggregate();
This adds a rating for a review <-I'm stuck here!
// this is some test code to add the rating review
$rating[0]['Price'] = 80;
$rating[0]['Value'] = 100;
$rating[0]['Quality'] = 80;
$product_id = 23;
$review_id = 631;
foreach ($rating as $ratingId => $optionId) {
// This is the bit where it all seems to go wrong!:
Mage::getModel('rating/rating')
->setRatingId(1)
->setReviewId($review_id)
->addOptionVote($val, $product_id);
}
Thanks!
This worked for me:
public function addReview($ratingarray)
{
$product_id = $ratingarray['product_id'];
$storeid = $ratingarray['store_id'];
$title = $ratingarray['title'];
$customerid = $ratingarray['customer_id'];
$nickname = $ratingarray['nickname'];
$detail = $ratingarray['detail'];
$review = Mage::getModel('review/review');
$review->setEntityPkValue($product_id);
$review->setStatusId(1);
$review->setTitle($title);
$review->setDetail($detail );
$review->setEntityId($review->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE));
$review->setStoreId($storeid);
$review->setStatusId(1); //approved
$review->setCustomerId($customerid);
$review->setNickname($nickname);
$review->setReviewId($review->getId());
$review->setStores(array($storeid));
$review->save();
$review->aggregate();
//return "success";
$rating_options = $ratingarray['options'];
/*array(
array(1,2,3,4),
array(6,7,8),
array(11,12)
);*/
$row = count($rating_options);
$rating_id = 1;
foreach($rating_options as $key1=>$val1)
{
foreach($val1 as $key2=>$val2)
{
$_rating = Mage::getModel('rating/rating')
->setRatingId($key1)
->setReviewId($review->getId())
->addOptionVote($val2,$product_id );
}
}
return "Success";
}
I am calling this like =>
$options = array(1=>array(1,2,3,4),2=>array(6,7,8),3=>array(11,12));
$reviewarray = array('customer_id'=>'21','product_id'=>'176','store_id'=>'4','title'=>'Review','nickname'=>'XYZ','detail'=>'Nice Product with Life time warrenty', 'options'=>$options);

Resources