Magento - How can I add rating information to a review - magento

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);

Related

DRY Coding in Laravel 7+

I have been using Laravel as a beginner for a few weeks now and i am seeking for knowledge.
I hope that you can help me!
I would like to clean up my project and its controllers.
I have two api refresh buttons which retrieves new orders and updates existing orders from an api.
One button is for a specific costcentre and the other button is for refreshing all orders at the same time.
Not to forget, it also updates the OrderProduct rows.
For this i have used the same code with just a little difference for each function.
While i like to not repeat the same.
Is there any solution for this?
Example current situation:
Specific costcentre
$order = new Order();
$order->costcentre_id = $costcentre->id;
$order->invoice = $row['invoice_prefix'] . $row['invoice_no'];
$order->customer_id = $row['customer_id'];
$order->firstname = $row['firstname'];
$order->lastname = $row['lastname'];
$order->email = $row['email'];
$order->telephone = $row['telephone'];
$order->save();
foreach ($product as $prod) {
$newprod = new Product();
$newprod->name = $prod->name;
$newprod->save();
}
All costcentres
foreach ($costcentre as $cc) {
$order = new Order();
$order->costcentre_id = $cc->id;
$order->invoice = $row['invoice_prefix'] . $row['invoice_no'];
$order->customer_id = $row['customer_id'];
$order->firstname = $row['firstname'];
$order->lastname = $row['lastname'];
$order->email = $row['email'];
$order->telephone = $row['telephone'];
$order->save();
foreach ($product as $prod) {
$newprod = new Product();
$newprod->name = $prod->name;
$newprod->save();
}
}

How to insert values in another table in controller joomla

I am using joomla 3.1.1 and joomshopping. i need to insert values in another table at same time when user register on website. In user controller i need to insert values in my custom table. can i use a direct insert query in my controller file. this is function in controller file to register user. Where i can put my code to insert data in another table.
function registersave(){
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$mainframe = JFactory::getApplication();
$jshopConfig = JSFactory::getConfig();
$config = JFactory::getConfig();
$db = JFactory::getDBO();
$params = JComponentHelper::getParams('com_users');
$lang = JFactory::getLanguage();
$lang->load('com_users');
$post = JRequest::get('post');
JPluginHelper::importPlugin('captcha');
$dispatcher = JDispatcher::getInstance();
$res = $dispatcher->trigger('onCheckAnswer',$post['recaptcha_response_field']);
if(!$res[0]){
JError::raiseWarning('','Invalid Captcha');
$this->setRedirect("index.php?option=com_jshopping&controller=user&task=register",'','',$jshopConfig->use_ssl);
}
else
{
JPluginHelper::importPlugin('jshoppingcheckout');
$dispatcher = JDispatcher::getInstance();
if ($params->get('allowUserRegistration')==0){
JError::raiseError( 403, JText::_('Access Forbidden'));
return;
}
$usergroup = JTable::getInstance('usergroup', 'jshop');
$default_usergroup = $usergroup->getDefaultUsergroup();
if (!$_POST["id"]){
}
$post['username'] = $post['u_name'];
$post['password2'] = $post['password_2'];
//$post['name'] = $post['f_name'].' '.$post['l_name'];
$post['mailing_list'] = $post['mailing_list'];
$hear = '';
$post['where_did_you_purchase'] = $post['where_did_you_purchase'];
$post['ages_of_your_children'] = $agesofchilderen;
$post['comments_or_suggestions'] = $post['comments_or_suggestions'];
$post['vehicle_2'] = $post['vehicle_2_model'].'-'.$post['vehicle_2_year'];
if ($post['birthday']) $post['birthday'] = getJsDateDB($post['birthday'], $jshopConfig->field_birthday_format);
$dispatcher->trigger('onBeforeRegister', array(&$post, &$default_usergroup));
$row = JTable::getInstance('userShop', 'jshop');
$row->bind($post);
$row->usergroup_id = $default_usergroup;
$row->password = $post['password'];
$row->password2 = $post['password2'];
if (!$row->check("register")){
JError::raiseWarning('', $row->getError());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1, $jshopConfig->use_ssl));
return 0;
}
$user = new JUser;
$data = array();
$data['groups'][] = $params->get('new_usertype', 2);
$data['email'] = JRequest::getVar("email");
$data['password'] = JRequest::getVar("password");
$data['password2'] = JRequest::getVar("password_2");
//$data['name'] = $post['f_name'].' '.$post['l_name'];
$data['username'] = JRequest::getVar("u_name");
$useractivation = $params->get('useractivation');
$sendpassword = $params->get('sendpassword', 1);
if (($useractivation == 1) || ($useractivation == 2)) {
jimport('joomla.user.helper');
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
//echo $row->getTableName();
//print_r($row);
//die("kkk");
$user->bind($data);
$user->save();
$row->user_id = $user->id;
unset($row->password);
unset($row->password2);
if (!$db->insertObject($row->getTableName(), $row, $row->getKeyName())){
JError::raiseWarning('', "Error insert in table ".$row->getTableName());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1,$jshopConfig->use_ssl));
return 0;
}
}
}
Try this,
Please do not edit Joomla core files.
If you need to add register data on your custom table the create a User Plugin.
Joomla provides lot of plugin events in your case you can use onUserAfterSave. event
Create a User plugin with onUserAfterSave event then simply use the Joomla DB library to your custom table entries.
Hope it helps..

how to import discount coupon csv file in magento admin

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>';

Use Tierprices of other customergroup

i'm trying to get my pricing extension working but i'm stucking at the tierprices.
If a visitor comes to my site i added a paramter to the cookie.
Example: http://www.foo.com/category/product.html?sidx=5
Now the visitor enters my site with the sidx parameter. Now the Observer: catalog_product_get_final_price sets the finalprice with the first tierprice of this Product of Customergroup 5.
The Customergroup of the visitor is still NOT LOGGED IN. Now i need the other tierprices of the Customergroup ID 5 without registering.
I have googled a lot to find a solution for that but i don't get the point.
Best Regards
boti
If you want to get the Tier prices for any product:
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID_HERE);
$tierPrices = $product->getData('tier_price');
if (!is_array($tierPrices)) {
$tierPrices = array();
}
$result = array();
foreach ($tierPrices as $tierPrice) {
$row = array();
$row['customer_group_id'] = (empty($tierPrice['all_groups']) ? $tierPrice['cust_group'] : 'all' );
$row['website'] = ($tierPrice['website_id'] ? Mage::app()->getWebsite($tierPrice['website_id'])->getCode() : 'all');
$row['qty'] = $tierPrice['price_qty'];
$row['price'] = $tierPrice['price'];
$result[] = $row;
}
// $result now has an array of all tier prices...
// looking for cust_group = 5 would be trivial:
foreach ($tierPrices as $tierPrice) {
if($tierPrice['cust_group'] == 5) {
return $tierPrice; // this is what you want..
}
}

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();

Resources