On the success page after checkout (success.phtml), I'd like to run a script only if a certain product ID has been bought. Is this possible?
I'm using Magento 1.4.2.
Try adding this to Success.phtml
$order = Mage::getModel('sales/order')->loadByIncrementId($this->getOrderId());
$items = $order->getItemsCollection();
$sku = $ids = array();
foreach($items as $item){
//$sku[] = $item->getSku();
$p_ids[] = $item->getProductId();
}
$p_id = 16;
if(in_array($p_id, $p_ids)){
//run script
}
This sort of logic might work on success.phtml page.
$
if($this->getOrderId()) {
$found = false;
$skuToFind = 'abc';
$order = Mage::getModel('sales/order')->loadByIncrementId($this->getOrderId());
$items = $order->getAllItems();
foreach ($items as $i => $item) {
if($item->getSku() == $skuToFind) {
$found = true; break;
}
}
if($found) { echo "Product Found"; } else { echo "No Found"; }
?>
Well, you only need to find the cart variables. I'm not sure the exact variables but echoing out the $_SESSION will show you where they are. Check out the following example code:
if(in_array('2324242', $_SESSION['product_ids'])
{//in this case 2324242 is the product ID you are looking for
//Require_once ('script');
//Or redirect to script.php
}
Related
Can someone help me simplify this complex nested if()'s algorithm? I know it can be simplified, but I'm afraid I'll mess up with the multiple conditions if I trust myself.
$groups = array();
foreach ($items as $item) {
if ($item['group_code']) {
if (array_key_exists($item['group_code'], $groups)) {
if (mb_strlen($groups[$item['group_code']]) < mb_strlen($item['title'])) {
$groups[$item['group_code']] = $item['title'];
}
} else {
$groups[$item['group_code']] = $item['title'];
}
} else {
$groups[$item['item_code']] = $item['title'];
}
}
What I want is to create an index of product titles in $groups. If the group_code key exists for each item, then I want to store the lengthier title of all items belonging to that group. If group_code doesn't exist (meaning it's a single product and not a grouped one), I want to store the title of that item using the item_code instead (this is the simplest condition, and no length comparison is needed here).
What about checking the else conditions first?
foreach ($items as $item) {
if (!isset($item['group_code'])){
$groups[$item['item_code']] = $item['title'];
} else if (!array_key_exists($item['group_code'], $groups)){
$groups[$item['group_code']] = $item['title'];
} else if (mb_strlen($groups[$item['group_code']]) < mb_strlen($item['title'])){
$groups[$item['group_code']] = $item['title'];
}
}
I'd simplify it like this (php 7+):
foreach ($items as $item) {
$t = $item['title'];
$c = $item['group_code'] ?? $item['item_code'];
if (mb_strlen($t) > mb_strlen($groups[$c] ?? '')) $groups[$c] = $t;
}
This might be a simple solution, however I am not able to come up with it, therefore any help is welcome.
I have a shopping basket so customers can add different items for it (as normal)
On some of these Items there are conditions and when added to the basket I'd like to show them up, however I have it setup so it checks for the value, but it only takes the value from the last added item.
Have the following
public function get_contents() {
$items = array();
foreach($this->items as $tmpItem) {
$item = null;
$item['Condition'] = $this->Conditions[$tmpItem];
$items[] = $item;
}
return $items;
}
foreach($this->items as $item) {
if(strstr($this->Conditions[$item], 'no') ==!false) {
$this->Conditions = 'no';
$item['Condition'] = $this->Conditions;
} else
$this->Conditions = 'yes';
$item['Condition'] = $this->Conditions;
What I would like to do is if any of these items contain the condition 'no'
$this->Conditions = 'no';
$item['Condition'] = $this->Conditions;
However it only takes the value of the last added item
Any help welcome
You are over riding the array element
foreach($this->items as $item) {
if(strstr($this->Conditions[$item], 'no') ==!false){
$this->Conditions = 'no';
$item[] = $this->Conditions;
}
else{
$this->Conditions = 'yes';
$item[] = $this->Conditions;
}
}
I can not seem to find any fault in this shopping-cart, but it is not displaying correctly.. I saw this YouTube video, and tried the code from there (https://www.youtube.com/watch?v=SlwMBtx0YMQ), but it had MySQL instead of MYSQL PDO; so I converted to PDO instead. I am echoing the class from another page to display the HTML-code. Yes, I am new to this..
The code is translated from Norwegian to English:
<?php
class shoppingCart {
// This function works as it should it seems like
function writeShoppingCart() {
$cart = $_SESSION["cart"];
if (!$cart) {
return "0 products";
} else {
$products = explode(",",$cart);
$number = (count($products) > 1) ? "s" : "";
return "<a href='cart.php'>".count($products)." Products ".$number."";
}
}
// But this function is not working as it should (?)
function showCart() {
$cart = $_SESSION["cart"];
if ($cart) {
$products = explode(",",$cart);
$content = array();
// FAULT HERE MAYBE ?
foreach ($products as $product) {
$content[$product] = (isset($content[$product])) ? $content[$product]+1 : 1;
}
$output[] = '<form action="cart.php?action=update" method="POST" id="cart"';
$output[] = '<table>'; // This was corrected by "jeyoung" (">")
// HERE ? $content .. I THINK
foreach ($content as $productID=>$qty) {
$sql = "SELECT * FROM Product WHERE ProductID = ".productID;
// FAULT HERE ....?
echo " WORKS HERE 1 "; // From here and down the code stops displaying ...
$result = $conn->query($sql);
echo " WORKS HERE 2 "; // This is just check-marks to make it easier to find the fault ..
$user_data = $result->fetch(PDO::FETCH_BOTH);
echo " WORKS HERE 3 ";
extract($user_data);
$output[] = '<tr>';
$output[] = '<td><a href="cart.php?action=delete&id='.$productID.'" > Delete </a></td>';
$output[] = '<td>'.$productName.'</td>';
$output[] = '<td>NOK '.$PriceNOK.',-</td>';
$output[] = '<td><input type="text" name="qty'.$productID.'" value='.$qty.' size="3" maxlength="3" /></td>';
$output[] = '<td> NOK '.($PriceNOK * $qty).',-</td>';
$totalCost += $PriceNOK * $qty;
$output[] = '</tr>';
echo " WORKS HERE 4 ";
}
$output[] = '</table>';
$output[] = '<p> Total: <strong>NOK '.$totalCost.',-</strong></p>'; // NOK = Norwegian Kroner (currency)
$output[] = '<button type="submit">Update Cart</button>';
$output[] = '</form>';
} else {
$output[] = '<p>Cart is empty.</p>'; // Cart empty
}
return join('',$output);
}
}
?>
There is an error in your function
function showCart() {
$cart = $_SESSION["cart"];
if ($cart) {
$output = explode(",",$cart);
$content = array();
// FAULT HERE MAYBE ?
foreach ($products as $product) {
Your foreach used $products but you do not have this variable. You need to assign that variable the way you do in the first function. Instead of
$output = explode(",",$cart);
use
$products = explode(",",$cart);
The "s" at the beginning of the code is not a typo, it should change product into products if needed.
On this line, $produksjon[] = '<table';, the tag is not closed properly.
It should be $produksjon[] = '<table>';.
I forgot to define $conn inside the ShoppingCart-class itself. I had only defined it outside! Did not know this was necessary.
I am working on opencart.I dont want to allow users to add same product multiple times in cart. for this i have a logic that i want to compare the products in cart. I will get the the product id of each product(how many the user added by clicking add to cart) than i will compare those ids. If they are same i will show them error message else they can carry on. For this logic i have used this code till now.
$products = $this->cart->getProducts();
foreach ($products as $product)
{
$p_id=$product['product_id'];
}
But i dont get that how will i compare 2 product ids in foreach loop. and than add my logic that if product ids are equal show error message.
You can simply check it at the time when user add a product to cart. To do so modify add function in controller->checkout->cart.php
In public function add() {
Add
$products = $this->cart->getProducts();
if($products){
foreach ($products as $product)
{
if($this->request->post['product_id'] == $product['product_id']){
$json['error']['blabla'] = 'Your warning message.';
break;
}
}
}
Before
if (!$json) {
And display that error wherever you want to display. That's it.
you can get the value of new product id and than compare it like this
//get product id to be added
$new_product = "get ID";
$products = $this->cart->getProducts();
foreach ($products as $product)
{
$p_id=$product['product_id'];
//compare with new product_id with existing
if ($_pid == $new_product){
echo " Product already exists!!";
}
}
$products = $this->cart->getProducts();
$exist = false;
foreach ($products as $product)
{
if ($p_id == $product['product_id']) {
$exist = true;
break;
}
}
if (!$exist) {
//add product co cart
}
Try this way
$products = $this->cart->getProducts();
$p_id = '';
foreach ($products as $product)
{
if($p_id != $product['product_id']) {
$p_id=$product['product_id'];
}else{
echo " Product already exists!!";
}
}
This will get you both a unique list of ID's and a list of ID's that needed to be removed to make the list unique.
// get the list of ID's
$products = $this->cart->getProducts();
$all = array();
foreach ($products as $product)
{
$all[] = $product['product_id'];
}
// Flip the array twice to just get the unique ID's
$unique = array_flip(array_flip($all));
// Get a list of ID's that were lost
$difference = array_diff_assoc($all, $unique);
Does anyone know how I can get a list of products belonging to a specific category from within a view file in Magento?
You can use magento object to filter.
Example:
$categoryId = 123; // a category id that you can get from admin
$category = Mage::getModel('catalog/category')->load($categoryId);
$products = Mage::getModel('catalog/product')
->getCollection()
->addCategoryFilter($category)
->load();
print_r($products);
It all depends on which view you're in. ;-)
First off, I hope you stayed within your template set (default in my example).
Use this as an example:
<?php
$_cat = $this->getCurrentCategory();
$_parent = $_cat->getParentCategory();
$_categories = $_parent->getChildren();
/* #var $category Mage_Catalog_Model_Category */
$collection = Mage::getModel('catalog/category')->getCollection();
/* #var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
$collection->addAttributeToSelect('url_key')
->addAttributeToSelect('name')
->addAttributeToSelect('is_anchor')
->addAttributeToFilter('is_active', 1)
->addIdFilter($_categories)
->setOrder('position', 'ASC')
->joinUrlRewrite()
->load();
$productCollection = Mage::getResourceModel('catalog/product_collection');
$layer = Mage::getSingleton('catalog/layer');
$layer->prepareProductCollection($productCollection);
$productCollection->addCountToCategories($collection);
// $productCollection should be ready here ;-)
?>
I'm using the above code to display sister categories in my template - it's not ideal but it works.
It's sort of a hack because I did not yet have time to learn all the layout XML madness. Otherwise if you use the XMLs you need to keep in mind - it all depends on where you are at. Where means the template file and essentially also the layout (in terms of app/design/frontend/default/default/layout/*).
I know it's not much, but I hope it helps to get you started.
Here is the code to get products from any particular category. You can use this in view file as well.
// if you want to display products from current category
$category = Mage::registry('current_category');
// if you want to display products from any specific category
$categoryId = 10;
$category = Mage::getModel('catalog/category')->load($categoryId);
$productCollection = Mage::getResourceModel('catalog/product_collection')
->addCategoryFilter($category);
// printing products name
foreach ($productCollection as $product) {
echo $product->getName();
echo "<br />";
}
<?php
$c_id = 2;
$category = new Mage_Catalog_Model_Category();
$category->load($c_id);
$collection = $category->getProductCollection();
$collection->addAttributeToSelect('*');
foreach ($collection as $_product) { ?>
<?php echo $_product->getName(); ?>
<?php } ?>
I pretty much needed the same. Here is how I have done it:
$prod_whole = array();
if(!empty($_menu)) //$_menu = array of Categories with some basic info
foreach($_menu as $v)
{
if($v['name']=='HOME')
continue;
$cat_id = $v['id'];
#/ Setup Products
$category = Mage::getModel('catalog/category')->load($cat_id);
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*') // select all attributes
->addCategoryFilter($category)
->setPageSize(8) // limit number of results returned
->setCurPage(0)
->load()
;
$prod_collection = array();
foreach ($collection as $product)
{
$prod_collection_1 = array();
#/ Basic Info
$prod_collection_1['id'] = $product->getId();
$prod_collection_1['name'] = $product->getName();
$prod_collection_1['price'] = (float) $product->getPrice();
//$prod_collection_1['desc'] = $product->getDescription();
//$prod_collection_1['short'] = $product->getShortDescription();
$prod_collection_1['type'] = $product->getTypeId();
$prod_collection_1['status'] = $product->getStatus();
$prod_collection_1['special_price'] = $product->getSpecialPrice();
$prod_collection_1['direct_url'] = $product->getProductUrl();
#/ getCategoryIds(); returns an array of category IDs associated with the product
foreach ($product->getCategoryIds() as $category_id)
{
$category = Mage::getModel('catalog/category')->load($category_id);
$prod_collection_1['parent_category'] = $category->getParentCategory()->getName();
$prod_collection_1['category'] = $category->getName();
//$prod_collection_1['category_idx'] = preg_replace('/[\s\'\"]/i', '_', strtolower(trim($prod_collection_1['category'])));
$prod_collection_1['category_id'] = $category->getId();
}
#/gets the image url of the product
$prod_collection_1['img'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();
$prod_collection[] = $prod_collection_1;
}//end foreach.....
$prod_whole[$cat_id] = $prod_collection;
}//end foreach categories.......
//var_dump('<pre>', $prod_whole);
Hope this helps.
<?php
$category_id = 10; // if you know static category then enter number
$catagory_model = Mage::getModel('catalog/category')->load($category_id); //where $category_id is the id of the category
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addCategoryFilter($catagory_model); //category filter
$collection->addAttributeToFilter('status',1); //only enabled product
$collection->addAttributeToSelect(array('name','url','small_image')); //add product attribute to be fetched
//$collection->getSelect()->order('rand()'); //uncomment to get products in random order
$collection->addStoreFilter();
if(!empty($collection))
{
foreach ($collection as $_product):
echo $_product->getName(); //get product name
endforeach;
}else
{
echo 'No products exists';
}
?>
You should always avoid putting code like this into a view, it's very bad practice.
You can also run into issues as views can be cached, leading to unexpected behaviour.
you should override the block you are using, placing code there. you can then call any new methods inside your view files.
for example, you could copy Mage_Catalog_Block_Product_List
from: app/code/core/Catalog/Block/Product/List.php
to: app/code/local/Catalog/Block/Product/List.php
you could then add a new method, possibly using some of the code mentioned in the above posts.
your new method would then be available inside your view file (list.phtml or any view using this block)
Here is a code to export all product with it's category into csv
<?php
set_time_limit(0);
ini_set("memory_limit",-1);
ini_set('max_execution_time','1800000000');
require_once '../app/Mage.php';
Mage::app();
$category = Mage::getModel('catalog/category');
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
$fp = fopen('category-product-export.csv', 'w');
$field = array('Product SKU','Category Name');
fputcsv($fp, $field);
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->load();
foreach ($_productCollection as $_product){
$cats = $_product->getCategoryIds();
$cnt = 0;
$catName = '';
foreach($cats as $id) {
$category->load($id);
$root = 'Root Catalog';
$isRoot = strtolower($root);
$categoryName = strtolower($category->getName());
if($categoryName == $isRoot){
continue;
}
$categories[$id]['name'] = $category->getName();
$categories[$id]['path'] = $category->getPath();
$path = explode('/', $categories[$id]['path']);
$len = count($path);
$string = '';
if($id > 2){
foreach ($path as $k=>$pathId)
{
$separator = '';
if($pathId > 2){
$category->load($pathId);
if($k != $len-1){ $separator = ' || ';}
$string.= $category->getName() . $separator;
}
}
if($cnt > 0) {
$catName.= ','.$string;
} else {
$catName = $string;
}
$cnt++;
}
}
//echo $catName;
$field = array($_product->getSku(),$catName);
fputcsv($fp, $field);
}
?>
Download