STRANGE...Not able to get cart items in magento on a custom page (only when the customer is logged in) - magento

Here is the standard code I am using for getting cart items and their attributes which works only when the customer is not logged in. As soon as I log in using my account this script stops working and does not return the items in the cart. Also the cart items count is also 0. But as soon as I close the browser(session ends..) and the script returns the cartitems correctly! Very strange, I have not been able to find out the cause. Please guide, anyone?
require_once('../app/Mage.php') ;
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName(); //HERE IS THE COMPLETE CODE:<?php
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
//Getting buyer's country label
$bcountry1 = $_REQUEST['country']; //gets country code
$_countries = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false);
foreach($_countries as $_country){
if ($_country['value']==$bcountry1){$bcountry = $_country['label'];}
}
//Fetching vendor for each product
$config = Mage::getConfig()->getResourceConnectionConfig("default_setup");
$dbinfo = array("host" => $config->host,
"user" => $config->username,
"pass" => $config->password,
"dbname" => $config->dbname );
$hostname = $dbinfo["host"];
$user2 = $dbinfo["user"];
$password = $dbinfo["pass"];
$dbname = $dbinfo["dbname"];
$dbhandle = mysql_connect($hostname,$user2,$password) or die("Unable to connect");
$selected = mysql_select_db("myart2",$dbhandle);
$Proceed=0;
//Getting all products in the cart
//echo $cart = Mage::getSingleton('checkout/cart')->getItemsCount();
// Secret Sauce - Initializes the Session for the FRONTEND
// Magento uses different sessions for 'frontend' and 'adminhtml'
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
$productname = $item->getName();
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $item->getSku(), array('manufacturer'));
$manufacturer = $product->getResource()->getAttribute('manufacturer')->getFrontEnd()->getValue($product);
$qry="select * from vendors WHERE company_name='$manufacturer'";
$result = mysql_query($qry) or die("Unable to run select query");
$row = mysql_fetch_array($result) or die("Unable to fetch data");
if( strcasecmp($row['country'],$bcountry)!=0 && $row['ships_abroad']!=1)
{$Proceed=1;$productnames[]=$productname;}
}
if($Proceed==1)
{
echo implode(',',$productnames);
}
else {echo 1; }
?>

I've tested the following four main permutations, and the code works in a stock CE1.7 instance in all cases:
Create guest quote
Convert guest quote to customer quote via login
Instantiate existing customer quote via login
Merge guest quote with customer quote via login
Adjust the server & app environment params as follows to view & rule out any errors (edit - added complete script; note the closing "}"):
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName();
}

Related

How can i update my products?

I want to update from my script the meta title, the meta description and the meta keywords for all of my products.
The meta title = the name of the product
The meta description = the short description of the product
The meta keywords is the meta keywords i've put from the category of the product.
I can loop and get the informations i want to make the update (except the meta keywords of the description) and after how i can make the update inside the loop ?
Thanks
<?php require_once 'app/Mage.php';
umask(0);
set_time_limit(0); // ignore php timeout
ignore_user_abort(true); // keep on going even if user pulls the plug*
while(ob_get_level())ob_end_clean(); // remove output buffers
ob_implicit_flush(true); // output stuff directly
//error_reporting(E_ALL);
/* not Mage::run(); */
Mage::app('default');
// get product collection (All product)
$storeId = Mage::app()->getStore()->getId();
$visibility = array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG);
$_productCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('visibility', $visibility)
->setStoreId($storeId)
->addStoreFilter($storeId);
foreach ($_productCollection as $pro) { // loop each product
$meta_title = $pro['meta_title'];
$meta_description = $pro['meta_description'];
$name = $pro['name'];
$short_description = $pro['short_description'];
// I want to update the meta_title, meta_description, meta_keywords
// meta_description = short_description
// meta_title = name
// meta_keywords = meta keywords from the category of the product
}
?>
You can easy set keyword and description by using standard setters.
Inside foreach loop just use :
foreach ($_productCollection as $pro):
$product = Mage::getModel('catalog/product')->load($pro->getId());
$product->setMetaTitle('Product Title')
->setMetaKeyword('Product keywords')
->setMetaDescription('Product Description')
->save();
endforeach;
Try this,
foreach ($_productCollection as $pro):
$product = Mage::getModel('catalog/product')->load($pro->getId());
$cats = $product->getCategoryIds();
$meta_keys = '';
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
if($_cat->getMetaKeywords())
$meta_keys .= $_cat->getMetaKeywords().', ';
}
$product->setMetaTitle($pro->getName())
->setMetaKeyword($meta_keys)
->setMetaDescription($pro->getShortDescription())
->save();
endforeach;

how I can get all product which i buy

I try write this code
public function allsalesblock(){
echo 'other block ';
$orders = Mage::getResourceModel('sales/order_collection')
->addFieldToSelect('*')
->addFieldToFilter('customer_id', Mage::getSingleton('customer/session')->getId());
->addAttributeToSort('created_at', 'DESC');
$order = Mage::getModel("sales/order")->load($orders); //load order by order id
$ordered_items = $order->getAllItems();
foreach($ordered_items as $item){
echo $item->getItemId(); //product id
echo $item->getSku();
echo $item->getQtyOrdered(); //ordered qty of item
echo $item->getName();
}
}
But this doesn't work - i see white screen. I found this code(and modification) here How can I display all products bought by a customer in magento?
You can get it using below code,
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$email = 'albert#example.com';
$_orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_email',$email);
foreach ($_orders as $order) {
$id[]= $order->getId();
}
//print_r($id);
foreach ($id as $order_id) {
$order = Mage::getModel('sales/order')->load($order_id);
#get all items
$items = $order->getAllItems();
$itemcount= count($items);
$data = array();
$i=0;
#loop for all order items
foreach ($items as $itemId => $item)
{
$data[$i]['name'] = $item->getName();
$data[$i]['price'] = $item->getPrice();
$data[$i]['sku'] = $item->getSku();
$data[$i]['id'] = $item->getProductId();
$data[$i]['qty'] = $item->getQtyToInvoice();
}
#displaying the array in order to see the products
echo '<pre/>';print_r($data);
}
here change the email address as you want to get products which that customer bought,
$email = 'albert#example.com';

Magento - Accessing a customer's wishlist

I would like to be able to load a customer's wishlist and return the product id's of the products within the list
I am using:
$wishList = Mage::getSingleton('wishlist/wishlist')->loadByCustomer($customer);
$wishListItemCollection = $wishList->getItemCollection();
The problem is that the arrays in the Item Collection are protected and I can't find any methods to extract the data.
Is there another way to do this?
You're very close to your target.
$wishList = Mage::getSingleton('wishlist/wishlist')->loadByCustomer($customer);
$wishListItemCollection = $wishList->getItemCollection();
if (count($wishListItemCollection)) {
$arrProductIds = array();
foreach ($wishListItemCollection as $item) {
/* #var $product Mage_Catalog_Model_Product */
$product = $item->getProduct();
$arrProductIds[] = $product->getId();
}
}
The array variable $arrProductIds will now contain the list of all Product IDs that have been wishlisted by that specific Customer.
Your code is correct. There may be customer is not loaded. here is code.
$customer = Mage::getSingleton('customer/session')->getCustomer();
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $item)
{
// do things
}
In any template, using magento 1.8, this works
Total: <?php echo $this->helper('wishlist')->getItemCount() ?>
// Items
$this->helper('wishlist')->getWishlist()->getItemCollection();
$wishList = Mage::getSingleton('wishlist/wishlist')->loadByCustomer($customer);
$wishListItemCollection = $wishList->getItemCollection();
foreach ($wishListItemCollection as $item)
{
//do your thing e.g. echo $item->getName();
}
Try this with product all details like name, images etc...
<?php
$customer = Mage::getSingleton('customer/session')->getCustomer();
if($customer->getId())
{
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $item)
{
echo $item->getName()."</br>";
echo $item->getId()."</br>";
echo $item->getPrice()."</br>";
echo $item->getQty()."</br>";
$item = Mage::getModel('catalog/product')->setStoreId($item->getStoreId())->load($item->getProductId());
if ($item->getId()) :
?>
<img src="<?php echo Mage::helper('catalog/image')->init($item, 'small_image')->resize(113, 113); ?>" width="113" height="113" />
<?php endif; } } ?>

Magento - Product Collection with the current user's Wishlist

Within a Magento php Controller, how can I get a Product Collection containing the products listed in the logged in user's (ie current user's) Wishlist.
I am getting the Wishlist using:
$wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer(Mage::getSingleton('customer/session')->getCustomer());
and this contains the correct number of items.
But I would like to get a Product Collection. I have tried:
$productCollection = $wishList->getProductCollection();
and
$productCollection = $wishList->getProductCollection()->addAttributeToSelect('id')->load();
but the Product Collection I get has a length of 0.
How do I get the Product Collection?
You can use the getWishlistItemCollection (see link for more details) off the wishlist helper to return a collection of items, you then need to get the product from the item.
I have been using the following code to create an associative array of the products, which I then use to determine if a product I am displaying in the list page is in the wishlist...hopefully this will help:
public function getWishList() {
$_itemCollection = Mage::helper('wishlist')->getWishlistItemCollection();
$_itemsInWishList = array();
foreach ($_itemCollection as $_item) {
$_product = $_item->getProduct();
$_itemsInWishList[$_product->getId()] = $_item;
}
return $_itemsInWishList;
}
Try this with product all details like name, images etc...
<?php
$customer = Mage::getSingleton('customer/session')->getCustomer();
if($customer->getId())
{
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $item)
{
echo $item->getName()."</br>";
echo $item->getId()."</br>";
echo $item->getPrice()."</br>";
echo $item->getQty()."</br>";
$item = Mage::getModel('catalog/product')->setStoreId($item->getStoreId())->load($item->getProductId());
if ($item->getId()) :
?>
<img src="<?php echo Mage::helper('catalog/image')->init($item, 'small_image')->resize(113, 113); ?>" width="113" height="113" />
<?php endif; } } ?>
$customer = Mage::getSingleton('customer/session')->getCustomer();
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $item)
{
// do things
}

get products by user id in magento

How to get user id of magento admin panel, suppose i have created a account in magento admin panel named as user1 and user2 and giving the permission to add a product, then i want to know that user1 entered product and as well as user2 entered product?
After a long try i got the solution.
It worked for me.
$session = Mage::getSingleton('customer/session');
$resource = Mage::getSingleton('core/resource');
$read= $resource->getConnection('core_read');
$event_attending = $resource->getTableName('event_attending');
$select = $read->select('event_id')
->from($event_attending)
->where('user_id = ?',$session->getId())
->order('event_date DESC') ;
$attending_events = $read->fetchAll($select);
$resultArray = '';$str='';
foreach($attending_events as $attEvent){
if($str!='')$str.=',';
$str.=$attEvent['event_id'];
}
//echo $str;
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()){
$events = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addFieldToFilter('entity_id', array('in' => array($str)))
->load();
//print_r($events->toArray());
return $events;
}
else
return '';
}
$user = Mage::getSingleton('admin/session')->getData();
$userId = $user->getUser()->getUserId();
$userEmail = $user->getUser()->getEmail();
$userFirstname = $user->getUser()->getFirstname();
$userLastname = $user->getUser()->getLastname();
$userUsername = $user->getUser()->getUsername();
$userPassword = $user->getUser()->getPassword();
$adminuser = Mage::getSingleton()->getUser();
$roleId = implode('', $adminuser->getRoles());
$userId = $adminuser->getId();

Resources