Magento get customer by Tax/VAT number field - magento

I am looking to something similar to this one (thats works with email), But instead of get the customer by email, i want to get him by the Tax/VAT number.
$customer = Mage::getModel('customer/customer')->setWebsiteId($website->getWebsiteId())->loadByEmail($customerEmail);
I found this example but its doesn't work.
$customer = Mage::getModel('customer/customer')->getCollection()->addAttributeToSelect('*')->addFieldToFilter('taxvat', $ss_5_last)->load();
Thank you.

If the attribute taxvat contains unique values, your approach was almost right. But the result of your second try returns a collection. I think you need a customer object, so try this one:
$customer = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToSelect('*')
->addFieldToFilter('taxvat', $ss_5_last)
->getFirstItem();
This returns a customer object you can work with. Caution: If taxvat does NOT contain unique values, this method could return the wrong customer, because it always returns the first item of a collection with more than one item.

Related

How do I display all products by descending SKU #'s in Magento?

I am trying to display all products on my website in every category by descending SKU #'s. Can't seem to figure out how to do this, any ideas?
The following snippet will give you the collection you want, you may need to add pagination yourself if necessary.
$collection = Mage::getModel("catalog/product")->getCollection();
$collection->setOrder('sku', 'DESC');
You'll also need to join on any extra attributes with joinAttribute(), since the catalog_product database storage follows the EAV pattern.
I think this should help. Go to Admin->Catalog->Attributes->Manage Attributes find SKU and enable SKU first. Then you have to go app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php. Find at line 119 and change
protected $_direction = 'asc';
Change to
protected $_direction = 'desc';

Magento cart sort by category_id

I am trying to sort out items in cart by categroy_id:
$cartItems = Mage::getModel("checkout/cart")->getItems()
->addFieldToSelect('name')
->addFieldToSelect('category_id')
->addAttributeToSort('category_id', 'ASC');
echo $cartItems->getSelect(); //debug info
foreach($cartItems as $item) {
echo $this->getItemHtml($item);
}
Magento complaints that method addAttributeToSort does not exists, had a look and of course it isn't defined.
What is the proper way of doing this query?
Otherwise,
you can try the following code:
$collection = Mage::getModel('checkout/cart')->getItems()
->addFieldToSelect('name')
->addFieldToSelect('category_id')
->addOrder('category_id', 'asc');
addAttributeToSort() does work on certain collections, but not the checkout/cart Model.
I hope this helps!
When you run Mage::getModel("checkout/cart")->getItems() you get a collection of quote items, not products. So there is no category_id on the table sales_flat_quote_item that you can access.
If you want access to the product you have to loop your collection of quote items and run ->getProduct() on each item. Then you could call functions on the product, like ->getCategoryIds() to get a list of category ids that has the product assigned to it.

How to find associated products from grouped product is they are disabled?

I am trying to get the associated products from a grouped product.I can do that, but not for the products that they are disabled. I tried a solution which mention to set : Use Flat Catalog Product to "NO" but i still can't. Any other ideas? I tried load a collection and use filters like IS_ENABLED OR DISABLED and by loading Models like
$product = Mage::getModel('catalog/product')->load($id);
$associatedProducts = $product->getTypeInstance(true)->getAssociatedProducts($product);
Any other ideas?
So lets look at the getAssociatedProducts() method of Mage_Catalog_Model_Product_Type_Grouped class. Here's the interesting part of it:
if (!Mage::app()->getStore()->isAdmin()) {
$this->setSaleableStatus($product);
}
$collection = $this->getAssociatedProductCollection($product)
->addAttributeToSelect('*')
->addFilterByRequiredOptions()
->setPositionOrder()
->addStoreFilter($this->getStoreFilter($product))
->addAttributeToFilter('status', array('in' => $this->getStatusFilters($product)));
As you can see Magento adds status to collection filter. Method getStatusFilters() returns product statuses to apply on filter. If you would look at the body of this method you would see that it returns basically $product->getData($this->_keyStatusFitlers).
This method needs to return 2 values (2 statuses). But it doesn't. Responsible for that is if statement before the collection set up:
if (!Mage::app()->getStore()->isAdmin()) {
$this->setSaleableStatus($product);
}
This parts will set only ENABLED status on the product status filters.
If you want to get disabled products from grouped product you have rewrite Mage_Catalog_Model_Product_Type_Grouped class and remove the if statement and/or set proper filters.
Let me know if you don't know how to rewrite a Magento class, then I will extend this answer.

Unexpected behavior in Magento collection filters used in loops

I'm seeing an unexpected behavior in collections that maybe someone can enlighten me on (or maybe it's a bit of PHP I don't grok) (sorry for the length of this post, but I had to include sample code and results).
My goal was to write a report where I get an order and it's order items, then go to the invoice and shipment data for the order and get the matching order item data from their items. I know that there is only one invoice and shipment for all orders, so even though Magento uses a 1-M relationship between orders and invoices/shipments, I can take advantage of it as if it were 1-1
I know that the items are all related using the order_item_id fields, so I tried to write a function that used the the following call -
$invoiceItem = $order
->getInvoiceCollection()
->getFirstItem()
->getItemsCollection()
->addFieldToFilter('order_item_id', $orderItem->getItemId())
->getFirstItem();
But that didn't results I expected, what I saw was the same invoice item returned regardless of the order item id used in the filter.
So, to try to understand the problem, I wrote the following small program to see how the queries where created.
<?php
require dirname(__FILE__).'/../app/Mage.php';
umask(0);
Mage::app('default');
$orders = Mage::getResourceModel('sales/order_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('state', 'processing')
->addAttributeToSort('created_at', 'desc')
->addAttributeToSort('status', 'asc')
->load();
foreach ($orders as $order) {
echo "\ngetting data for order id ". $order->getId();
$items = $order->getAllItems();
$invoice = $order->getInvoiceCollection()->getFirstItem();
foreach ($items as $orderItem) {
echo "\n\ngetting data for order item id ". $orderItem->getItemId();
$invoiceItems = $order
->getInvoiceCollection()
->getFirstItem()
->getItemsCollection()
->addFieldToFilter('order_item_id', $orderItem->getItemId());
echo "\n".$invoiceItems->getSelect();
}
die; //just quit after one iteration
}
The output from this program was the following -
getting data for order id 7692
getting data for order item id 20870
SELECT `main_table`.* FROM `sales_flat_invoice_item` AS `main_table` WHERE (parent_id = '7623') AND (order_item_id = '20870')
getting data for order item id 20871
SELECT `main_table`.* FROM `sales_flat_invoice_item` AS `main_table` WHERE (parent_id = '7623') AND (order_item_id = '20870') AND (order_item_id = '20871')
getting data for order item id 20872
SELECT `main_table`.* FROM `sales_flat_invoice_item` AS `main_table` WHERE (parent_id = '7623') AND (order_item_id = '20870') AND (order_item_id = '20871') AND (order_item_id = '20872')
As you can see, every time though the loop another "AND (order_item_id =" was added for each item Id that I was filtering on. I thought that every time though the loop, I'd be getting a fresh version of the collection from using $order->getInvoiceCollection().
So, can anyone tell me what's going wrong in my sample code and educate me on the correct way to do this?
Thanks!
Regarding your business question: need more info. Is the goal to generate a collection with order item objects which are EACH aware of invoice and shipment details? It seems like there are rendering concerns getting pushed into modeling concerns.
Regarding the select statement question: Varien collections have an optimization which prevents them from accessing the storage backend more than once. This standard behavior is achieved in DB collection instances by setting the _isCollectionLoaded property to true.
In your case, the invoice collection instance is created via the order instance stored in a protected property, and immediately load()ed via IteratorAggregate (invoked via foreach). Because you are using the same order object instance in each iteration, you are dealing with this loaded invoice collection instance and are effectively calling addFieldToFilter(/* next order id */) with each iteration, resulting in the ever-expanding WHERE clause. This specific optimization can easily be worked around by calling $order->reset(). This brings us back to the salient issue though, which is the need to better understand the goal and (likely) use a custom collection or to manipulate a collection to join in the specific data that you need.

Retrieve all product IDs associated with a Catalog Price Rule in Magento

I need a way to retrieve product IDs associated with a Catalog Price Rule promotion (ex. 50% the price of all items in the BICYCLES category). I'd like to do this without having to iterate through the entire product database.
I know there is a function called getRuleProductIds($ruleID), which should return an array of product IDs by rule ID, but I have no idea where to use it, which collection to associate it with, etc.
I have the following code in a products_in_promotion.phtml template:
<?php
$rules = Mage::getModel('catalogrule/rule');
$collection = $rules->getCollection();
$sale_items = $collection->getRuleProductIds(1); # ??????? this throws an error
?>
$collection properly stores an array of all the Catalog Price rules, but that's as close as I can get. No product list is in sight.
Any ideas what I'm doing wrong here?
You don't have to get it as a collection. Just load the rule that you want and use getMatchingProductIds as found in Mage_CatalogRule_Model_Rule (aka catalogrule/rule).
$catalog_rule = Mage::getModel('catalogrule/rule')->load(1); // Rule ID
$skus = $catalog_rule->getMatchingProductIds();
var_dump($skus);
hth
If you have many products in your store then this is the efficient way. You may add website_id, custom_group_id in where class to be more specific.
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_read');
$tableName = $resource->getTableName('catalogrule_product');
$productIdList = $connection->fetchAll('SELECT product_id as product_id FROM '.$tableName.' WHERE rule_id = 1);
It worked for me after adding website filter to the code suggested by seanbreeden.
$catalog_rule = Mage::getModel('catalogrule/rule')->load(1); // Rule ID
$catalog_rule->addWebsiteFilter('1');
$skus = $catalog_rule->getMatchingProductIds();
var_dump($skus);

Resources