In Prestashop, how to get category of last product added? - smarty

I don't have that much experience with Prestashop, php, and Smarty.
How do I get the category of lastProductAdded?
I am trying to make the "continue shopping" button redirect to the category of the last product added.
« {l s='Continue shopping'}
The following code doesn't seem to work, giving category id of 0 for some reason. (I have no idea whether it makes sense either)
Any help would be much appreciated. Thank you!
(The variable lastProductAdded and function getCategoryLink are already defined in-built)

For Prestashop 1.4.x you need to modificate Cart::getLastProduct() with this code:
public function getLastProduct()
{
$sql = '
SELECT cp.`id_product`, cp.`id_product_attribute`, p.`id_category_default`
FROM `'._DB_PREFIX_.'cart_product` cp
JOIN `'._DB_PREFIX_.'product` p ON (cp.`id_product` = p.`id_product`)
WHERE `id_cart` = '.(int)($this->id).'
ORDER BY cp.`date_add` DESC';
$result = Db::getInstance()->getRow($sql);
if ($result AND isset($result['id_product']) AND $result['id_product'])
return $result;
return false;
}
Regards

you need to use $lastProductAdded.id_category_default instead of $lastProductAdded.category->id
Regards

Related

Getting product name and phone number in the success page for Magento

I am using Magento 1.9 and I need to use customer name, number, and product name in the success page. How can I achieve that?
get customer name and phone number using below fields
$order = Mage::getModel('sales/order')->load($this->getOrderId());
if($order->getCustomerIsGuest()){
echo $order->getBillingAddress()->getName();
echo $order->getBillingAddress()->getTelephone();
}
else{
echo $order->getCustomerName();
echo $order->getTelephone();
}
Assuming you already have the order object in success page
$order->getBillingAddress()->getTelephone();
$order->getCustomerName();
$ordered_items = $order->getAllVisibleItems();
foreach($ordered_items as $item)
$product_name[] = $item->getName();
Even if some one searching for same.
$orderDetails = Mage::getModel(‘sales/order’)->loadByIncrementId($this->getOrderId());
To get Contact Number
echo $telePhone=$orderObj->getBillingAddress()->getTelephone();
To get Complete array use print_r($orderDetails);

Magento 1.9.1.1 - Duplicate results displayed

I have a Magento issue. I'm using Magento ver. 1.9.1.1.
The issue is that I am seeing duplicate results for a page which contains a list of jobs (its a recruitment page). The problem is each of the results is duplicated. I've never done any real Magento development before and it seems like a steep learning curve.
I've checked the content and that has only been entered once.
This is the offending code:
//I tried this line with no effect
//$collection = Mage::getModel('cms/page')->getCollection()->distinct(true);
// $collection contains the duplicate results
$collection = Mage::getModel('cms/page')->getCollection();
Can anyone give me any ideas on how I can solve this? Even an idea of where to look in the code would be good.
I've found two data structures when iterating through the collection. These are _origData and _Data. Don't know why its using both of these but I managed to fix/hack it by doing:
if($key == "_origData"){
continue;
}
Surely there's a better way to do this?
Thank you in advance :)
Have you tried applying filters to your collection?
See below:
$getStoreId = Mage::app()->getStore()->getId();
$collection = Mage::getModel('cms/page')->getCollection()
->addStoreFilter($getStoreId)
->addFieldToFilter('is_active', 1);
Resources:
Class Mage_Cms_Model_Mysql4_Page_Collection
You can see the code details on above mentioned Model class.But if you want custom code you can try like this :
$collection = Mage::getModel('cms/page')->getCollection();
$collection->getSelect()
->join(
array('s' => $collection->getTable('cms/page_store')),
's.page_id = main_table.page_id AND s.store_id != 0',
array('store_id')
)
->columns(array('stores_count' => new Zend_Db_Expr('COUNT(s.store_id)')))
->group('main_table.page_id')
->having('stores_count = ?', 1)
->having('s.store_id = ?', $storeId)
;

Magmi overwriting position of products in category

I'm using Magmi to import products into my Magento store. Categories are created on the fly and products are imported. All is working well.
Except for one thing: each time I run a Magmi import, the position of the product in the Magento category is set to 0. This way I cannot sort my products on position.
I have searched the Magmi wiki and github for someone who has run into the same problem, but didn't find anything.
Anyone familiar with this issue and is there a way to avoid it?
I wait too long an answer and do it myself, here is a fix:
my fix works other way - category positions clear only if you add $item["category_reset"] == 1; param to product params.
:1280 sting(in current magmi version) or find the public function assignCategories($pid, $item) in magmi_productimportengine.php.
ater
$cce = $this->tablename("catalog_category_entity");
$ccpt = $this->tablename("catalog_category_product");
add next code:
$sql = "SELECT $ccpt.*
FROM $ccpt
JOIN $cce ON $cce.entity_id=$ccpt.category_id
WHERE product_id=?";
$currentPositions = $this->selectAll($sql,$pid);
then change category reset:
if (!isset($item["category_reset"]) || $item["category_reset"] == 1)
{...}
to
if (isset($item["category_reset"]) && $item["category_reset"] == 1)
{
$sql = "DELETE $ccpt.*
FROM $ccpt
JOIN $cce ON $cce.entity_id=$ccpt.category_id
WHERE product_id=?";
$this->delete($sql, $pid);
$currentPositions = array();
}
after this change block with positioning
foreach ($catids as $catdef)
{...}
to:
// find positive category assignments
if (is_array($currentPositions) && count($currentPositions)) {
foreach ($currentPositions as $currentPosition) {
$catPos[$currentPosition['category_id']] = $currentPosition['position'];
}
}
foreach ($catids as $catdef)
{
$a = explode("::", $catdef);
$catid = $a[0];
if (count($a) > 1 && $a[1] != 0) {
$catpos = $a[1];
}
else {
if (isset($catPos[$catid]) && $catPos[$catid] != 0) {
$catpos = $catPos[$catid];
}
else {
$catpos = "0";
}
}
$rel = getRelative($catid);
if ($rel == "-")
{
$ddata[] = $catid;
}
else
{
$cdata[$catid] = $catpos;
}
}
if you dont import position, your current position will save. If it 0, it stay 0.
for clear actual position - add param to product item:
$item["category_reset"] == 1;
or change string back:
if ($item["category_reset"] == 1)
{ ....}
to:
if (!isset($item["category_reset"]) || $item["category_reset"] == 1)
{...}
Only a comment but since I'm a long-time reader but never setup an account and can't leave a comment directly with no rep. I know this is an old post, but I just found it and used AlexVegas's code above (thank you!). Worked almost fine for me, but in my case I still wanted the categories to fully reset to only what was in my Magmi import but I wanted the positions to remain intact. As-is above, the categories only append to the existing unless you use the category_reset column in your import, and if you do that it also resets the position.
If you're like me and want only the position to remain intact, but allow Magmi to overwrite the categories each time, use Alex's code above but tweak it a little
Where he says to change
if (!isset($item["category_reset"]) || $item["category_reset"] == 1)
{...}
to
if (isset($item["category_reset"]) && $item["category_reset"] == 1)
{
$sql = "DELETE $ccpt.*
FROM $ccpt
JOIN $cce ON $cce.entity_id=$ccpt.category_id
WHERE product_id=?";
$this->delete($sql, $pid);
$currentPositions = array();
}
Don't change it. It's that simple. In his code it prevents the category reset unless the column is specified, which is why the if statement gets changed. If the column exists, it also wipes out the currentPositions array that stores the current positions within the categories so those get reset as well.
If you want to append to the categories unless category_reset is in your import, but don't want to overwrite the positioning, use Alex's code as it is above in his answer but leave out
$currentPositions = array();
That way it won't overwrite the array that is storing the positions within the categories
Not an actual solution-
You can try using this plugin
http://www.magentocommerce.com/magento-connect/c3-category-position-import-export-extension.html/
You can ignore UPDATE position if exist
category creator/importer v0.2.5
at line 1248 replace with
if (count($inserts) > 0) {
$sql = "INSERT IGNORE INTO $ccpt (`category_id`,`product_id`,`position`) VALUES ";
$sql .= implode(",", $inserts);
// $sql .= " ON DUPLICATE KEY IGNORE";
$this->insert($sql, $data);
unset($data);
}
The Magmi wiki specifically mentions item positioning functionality here See quoted text below. This seems to describe exactly the functionality you are looking for? I have not tested it myself.
Quote:
Item positioning
From magmi 0.7.18 , category_ids column has been enhanced with item positioning. This feature is also supported in category importer from version 0.2+ (since category importer plugin is roughly a category_ids generator)
Sample
store,sku,....,categories
admin,00001,.....,cat name with \/ in the name and positioning::3
<= here we "escaped" the tree separator with a backslash , the category will be created as "catname with / in the name and positioning"
sku 00001 will be set with position 3 in the category
End quote

Magento 1.7: Unable to incorporate joinField in product collection

I'm having a problem where I can't get add joinField() to a product collection.. I have no clue why it doesn't work because it should be really simple or throw some errors at least. Needless to say, it is driving me nuts. I'm interested in looking at products and the total dollar amount in sales from them. This is what I have from a book called "Magento PHP Developer's Guide" and the Magento Wiki.
public function getProducts($categoryId) {
$productCollection = Mage::getModel('catalog/category')->load($categoryId)
->getProductCollection()
->joinField('o', 'sales_flat_order_item', array('o.row_total', 'o.product_id'), 'main_table.entity_id = o.product_id');
}
// die; when uncommented, this function WILL NOT die here
return $productCollection;
}
I'm getting the ->joinField() method right out of the book, but it doesn't grab any product. Strangely, the function doesn't even return anything because when the die line is uncommented, the function does not terminate there. Instead, the front-end will simply just skip this function without throwing any errors (that I can see at this time) and just doesn't display any blocks using this function. What am I missing here?
It works when I remove joinField() like below.
$productCollection = Mage::getModel('catalog/category')->load($categoryIds)
->getProductCollection();
UPDATE:
Further testing show that the following works. Note that if I use main_table instead of e, it does not work. If I look at the query generated from this, main_table is not replaced by the main table; instead, query contains the literal string "main_table".
$productCollection = Mage::getModel('catalog/category')->load($categoryIds)
->getSelect()
->join(array('o' => 'sales_flat_order_item'),
'e.entity_id = o.product_id',
'o.row_total'
);
While this doesn't.
$productCollection = Mage::getModel('catalog/category')->load($categoryIds)
->joinTable(
array('o' => 'sales_flat_order_item'),
'e.entity_id = o.product_id',
'o.row_total'
);
Maybe I don't see some simple mistake.. but I just don't see what's wrong.
public function getProducts($categoryId) {
$productCollection = Mage::getModel('catalog/category')->load($categoryId)
->getProductCollection()
->joinTable( // JoinTable makes more sense.
array('o' => 'sales/order_item'),
'main_table.entity_id = o.product_id'
array('row_total'),
)
;
return $productCollection;
}
It will probably return all fields in the catalog_product_entity table PLUS the row_total from the sales_order_item table. You might be able to use addAttributeToSelect('o.product_id') right before the join, just to clear the unwanted fields.

How to get last running transaction Id in magento

How can I get the last running transaction Id ? (eg: 10000001)
I've tried numerous ways, with no success.
I was suddenly enlightened when I looked at the problem again at home. Why not get the last order increment id from the sales/order collection?
$orders = Mage::getModel('sales/order')->getCollection()
->setOrder('increment_id','DESC')
->setPageSize(1)
->setCurPage(1);
echo $orders->getFirstItem()->getIncrementId();
Tested and working on Magento 1.3.2.3
Try this:
$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$dbc_collect_order = Mage::getSingleton('core/resource')->getConnection('core_read');
$items_collect_order = $dbc_collect_order->fetchAll("SELECT `increment_id` FROM `sales_flat_order` ORDER BY `entity_id` DESC LIMIT 1");
echo $last_main_order_id = $items_collect_order['0']['increment_id'];
Please note that there is a more simpler answer to silvo's:
$orders = Mage::getModel('sales/order')->getCollection();
echo $orders->getLastItem()->getIncrementId();

Resources