Magento Collection Issue. Determining Order In Iteration - magento

I have a category titled 'top 100 products' and , for now, the collection works fine. But what I want to do is dynamically deteremine what # each product is, in relation to the 100 products being listed. In other words, if product one is listed, I can grab the value so I can add "#1" next to the product title.
When product #74 is listed, it will dynamically say "#74". I can calculate the total number of listings using the getSize function but I don't know how to work with that varible to spit out the proper 'sequence' number of each listed product. The reason I use getSize is so the count can be preserved through paging.
To understand the code, please reference the /catalog/product/list.phtml template. In list or grid mode, you will see the following:
Edit. I can't post this code here. It's maddening. Just need to know how to get a while loop to surround the 'foreach' product contorller loop so I can use while (x) < variable_with_total_products_counted and let x++ reside within the product controller for loop. Every time I try to do this, I get syntax errors. As if it won't let the product controller loop (the for each loop) reside inside my while loop which iterates from 0 --> 99 (top 100 products).

How about something like this:
$count = $collection->getSize();
$counter = 1;
foreach($collection as $item) {
// Process item
echo '<p>' . $item->getName . ' (' . $counter . ')</p>';
$counter++;
}
To ensure that number is persistent, you can assign it to the products and it will stay assigned for the duration of the script / page:
$count = $collection->getSize();
$counter = 1;
foreach($collection as $item) {
$item->setData('tmp_number', $counter);
$counter++;
}
// Work with products

Related

Magento Buy X Get Y free Price rules

I have added new rule in Magneto for buying x product and getting y free . I have added a configurable product with multiple simple products . This rule works fine if I buy two of simple products with same sku values. What I want is that if user buys two simple products with different sku they should get second free .
How can i achieve this ?
This cannot be done with the default implementation of cart rules. You need to create new module and add your own type of rule to the list. I have made once such a module, in the following manner:
1) I add my own option to action dropdown. Luckily there is an event adminhtml_block_salesrule_actions_prepareform where you can hook. I used something like this
$form = $observer->getEvent()->getForm();
$options = $form->getElement('simple_action')->getValues();
$options[] = array(
'value' => self::BUY_ANY_X_GET_Y_ACTION,
'label' => Mage::helper('mymodule')->__('Extended Buy X get Y free (search all cart, discount amount is Y)'),
);
$form->getElement('simple_action')->setValues($options);
2) Then I hook into salesrule_validator_process where I checked whether cart items match the rule.
This was a little bit tricky as this validator is run for each cart item so you have to count how many times it was called and which items you have checked. I used conditions tab to prepare rules that says which X items have to be bought in order to get Y items according to conditions in actions tab.
With the first run of the validator you iterate over all cart collection and divides all products in two groups: one contains items that met criteria set by conditions tab, the second one met the criteria set by actions tab. In other words you form two arrays that contains items for X and items for Y.
foreach($quote->getItemsCollection() as $item) {
if (!$item->hasParentItemId()) {
if ($rule->getActions()->validate($item)) {
$ruleItems['y'][] = $item;
}
foreach($rule->getConditions()->getConditions() as $condition) {
foreach($condition->getConditions() as $check) {
if ($check->validate($item)) {
$ruleItems['x'][] = $item;
}
}
}
}
}
You calculate how many X's are there and how many Y's products will get discount. The when the event is called for each item you check if the item is in Y array and if there is enough discounts left for that item. If so you need to set discount amount and base discount amount calculated as item_qty * price and item_qty * base_price respectively. You need to set those values on result object that is in data passed to the observer method like:
$item = $observer->getEvent()->getItem();
$result = $observer->getEvent()->getResult();
$result->setDiscountAmount($item->getQty * $item->getPrice());
$result->setBaseDiscountAmount($item->getQty * $item->getBasePrice());

Can you Clone a collection row in Magento?

I'm trying to build a custom grid in Magento, where I have a row for every product ordered including qty. For example, if a customer ordered 3 of a specific product - I need to have 3 rows that all have matching details. Is this possible?
This is for a custom product where each row represents a manufacturing run. I'm not necessarily looking for code examples, but I'm not sure if I can do this with the sql style collection process? Or if I need modify the query and loop through once I've colelcted all the data from the database?
Thanks
Instead of showing the product order item grid, I just added an export to xml button. Then, in the grid just modified the "_exportIterateCollection" method as the following:
foreach ($collection as $item) {
for($i = 0; $i < $item->getQtyOrdered(); $i++ ){
call_user_func_array(array($this, $callback), array_merge(array($item), $args));
}
}
Hope this helps future questions!

Magento - Get total number of items of a category in view.phtml

How can I get the total number of Items, I want to show it in the category view.phtml file. Usually this value is in the Toolbar.phtml.
I have tried something like this, but I think I am pretty far away:
$this->helper('catalog/output')->$_productCollection->count()
Magento version 1.7.0.2
The expected result should be something like this:
Items in this category: 17
The 17 should be the total number. If possible should include subcategory items.
Assuming that you want to display it in view.phtml you already have the current category object there so you can use $_category->getId()
$products_count = Mage::getModel('catalog/category')->load($_category->getId())
->getProductCount();
echo($products_count);
If you want to use it in list.phtml you can use
echo($_productCollection->count());
Try this,
<?php $_helper = $this->helper('catalog/output');?>
<?php $_category_detail = Mage::registry('current_category');?>
<?php $_category_detail->getName();?>
<?php $_category_detail->getId(); ?>
<?php $products_count = Mage::getModel('catalog/category')->load($_category_detail->getId())
->getProductCount();
echo($products_count);
?>
Basically, you can't show the total amount of filtered items in your view.phtml.
the reason is, that the logic, which gets the total amount, is not present in the $this context of the view.phtml.
But the logic is available in the Mage_Catalog_Block_Product_List_Toolbar block which is a child block of Mage_Catalog_Block_Product_List, though.
that basically means that you can actually get the total amount of filtered items by instantiating a toolbar and list block.
After doing that, the collection of the toolbar block has to be set with the value of the collection of the list block.
the following code is used in the view.phtml file to get the filtered total amount of items from the toolbar block:
$toolbar = new Mage_Catalog_Block_Product_List_Toolbar();
$list = new Mage_Catalog_Block_Product_List();
$toolbar-> setCollection($list -> getLoadedProductCollection());
$products_count = $toolbar -> getTotalNum();
There can be two ways we can find product count of a category.
$collection = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('level')
->addAttributeToSelect('entity_id');
foreach($collection as $cat)
$cat->getProductCount();
This will give you the product count for deepest category only. So for example, you have following categories. considering tree like structure.
Clothes(6)
->Cotton(3)
->Women(2)
The result returned from the piece of code given above.
Clothes(3)
Cotton(1)
Women(2)
There are three products directly associated with Clothes only, 1 with Cotton only and 2 with Women only. So it simply ignores the subcategories.
Another way is getting product count from products perspective.
$current_category = Mage::getModel('catalog/category')->load($cat->getEntityId());
$productCount = Mage::getModel('catalog/product')->getCollection()
->addFieldToFilter('manufacturer',$this->manufacturer["id"])
->addFieldToFilter('visibility',4)
->addFieldToFilter('status',1)
->addCategoryFilter($current_category)->getSize();
This gives us the added benefit of filtering product attributes. However in the above scenario, the count returned will be slightly different.
It will return Clothes (6), as it has 3 products associated to itself and 3 more products to its sub categories. Similarly
Cotton(3)
Women(2).
So for efficient results it would be nice to use mix of both.
It's not right to load additional model inside view because you already have model instance from which you can retrieve Product collection.
$this->getCurrentCategory()->getProductCollection()->count();
it is very simple and it worked well for me its just one line of code
<?php echo Mage::registry('current_category')->getProductCount();?>
It will display the count of the products of current category

Pagination class in Custom Module in joomla

I am developing one custom search module in joomla. so I am using joomla's in-built database connection and function.
Problem is that I want to use pagination class in this module but don't know any hint.
Please help me on this.
Thanks.
Step 1: Get the total number of items in your database
ex: select count(*) from #__some_table where ....
Step 2: Import joomla pagination and create pagination object
jimport('joomla.html.pagination');
$pagination = new JPagination($total, $limitstart, $limit);
where
$total = total number of items that you count in step 1
$limit = total number of items you want to display on a page
$limitstart = index of the first item in the page. For example if you have 20 items per page, 0 is start index for 1 page, 20 is start index for second and so on.
Step 3: Show pagination on your page
echo $pagination->getPagesLinks();
echo $pagination->getPagesCounter();

How can I add "Quantity" to a VirtueMart "Browse" page?

My VirtueMart shop.browse page has the typical columns of SKU, Name, Price, and "Update" (which contains the Add to Cart button). I would like to add a Quantity column between Price and Update so that a buyer can choose a quantity prior to pressing the "Add to Cart" button.
Though I don't know HOW to do this, I think I know WHERE to do it:
/public_html/components/com_virtuemart/themes/default/templates/browse/includes/browse_listtable.tpl.php
Lines 67-72 of that file tell the program how to build the table, but what I DON'T know how to do is modify the code source to tell it to include quantity as an element for the table. Here's the code:
// Loop through each row and build the table
foreach($data as $key => $value) {
$table->addRow( $data[$key], 'class="sectiontableentry'.$i.'"', 'td', true );
$i = $i == 1 ? 2 : 1;
}
Which include file is actually being called in this foreach loop, and what code would I add to reference quantity data?
You should not modify your core code. If you just need to put quantity box inside your browse template use variable $form_addtocart
It will give you quantity box and add to cart button.
All variables for browse page and for flypage template you can find here:
http://virtuemart.net/documentation/Developer_Manual/Modifying_the_Layout.html
If this is not what you are trying to get, please be more specific, or show your web page.

Resources