Showing posts with label Magento Categories. Show all posts
Showing posts with label Magento Categories. Show all posts

Thursday, November 21, 2013

Magento : AddAttributeToFilter( Contionals - Getting products from the table in magento commerce



AddAttributeToFilter( Contionals - Getting products from the table in magento commerce ADDATTRIBUTETOFILTER CONDITIONALS IN MAGENTO

addAttributeToFilter is a function that can be called on a product collection in Magento. In short, it adds a condition to the WHERE part of the MySQL query used to extract a product collection from the database.




1
2
3
4
$_products = Mage::getModel('catalog/product')->getCollection()
   ->addAttributeToSelect(array('name', 'product_url', 'small_image'))
   ->addAttributeToFilter('sku', array('like' => 'UX%'))
    ->load();




The above code would get a product collection, with each product having it's name, url, price and small image loaded in it's data array. The product collection would be filtered and contain only products that have an SKU starting with UX.
addAttributeToFilter Conditionals
Notice above, I used the LIKE operator There are many more operators in SQL and addAttributeToFilter will accept them all. I include them below as well as a reference for you. Hopefully this will save you some time.
Equals: eq




1
$_products->addAttributeToFilter('status', array('eq' => 1));




Not Equals - neq




1
$_products->addAttributeToFilter('sku', array('neq' => 'test-product'));




Like - like




1
$_products->addAttributeToFilter('sku', array('like' => 'UX%'));




One thing to note about like is that you can include SQL wildcard characters such as the percent sign.
Not Like - nlike




1
$_products->addAttributeToFilter('sku', array('nlike' => 'err-prod%'));




In - in




1
$_products->addAttributeToFilter('id', array('in' => array(1,4,98)));




When using in, the value parameter accepts an array of values.
Not In - nin




1
$_products->addAttributeToFilter('id', array('nin' => array(1,4,98)));




NULL - null




1
$_products->addAttributeToFilter('description', 'null');




Not NULL - notnull




1
$_products->addAttributeToFilter('description', 'notnull');




Greater Than - gt




1
$_products->addAttributeToFilter('id', array('gt' => 5));




Less Than - lt




1
$_products->addAttributeToFilter('id', array('lt' => 5));






Greater Than or Equals To- gteq




1
$_products->addAttributeToFilter('id', array('gteq' => 5));




Less Than or Equals To - lteq




1
$_products->addAttributeToFilter('id', array('lteq' => 5));




addFieldToFilter()
Debugging The SQL Query
There are two ways to debug the query being executed when loading a collection in Magento.




1
2
3
4
5
6
7
// Method 1
Mage::getModel('catalog/product')->getCollection()->load(true);
// Method 2 (Quicker, Recommended)
$collection = Mage::getModel('catalog/product')->getCollection();
echo $collection->getSelect();




Both method 1 and method 2 will print out the query but both will do it in slightly different ways. Method 1 prints the query out as well as loading the products while method 2 will just convert the query object to a string (ie. will print out the SQL). The second method is definitely better as it will be executed much

By PHP with 36 comments

Friday, May 17, 2013

Magento - Check Current page is Category | DETERMINE IF CURRENT PAGE IS A CATEGORY

After a great deal of frustration and numerous tantrums I discovered the solution is to wrap the code in a loop that checks if it’s a category page.
//LOOP TO CHECK IF ITS A CATEGORY PAGE //INNER LOOP getId() == 5):?>
Shows this paragraph is the category id="5"
Else show this for different category pages
> //SHOW THIS CONTENT IF ITS A CMS PAGE
Else show this paragraph for all other pages
>
Posted in All, News, Tutorials and tagged eCommerce, Magento, Magento Category, Magento current_category, Mangento If Category.

========================

 Magento Determine if Current Page is Category or Not

Sometimes you find your self in the need to determine if the current page a visitor is viewing is of a category or not. The reason for this could drastically very, but one good reason is the need for a global element not be shown on any category page.
It would be much faster to simply include this element or rather custom block globally to your Magento store via your layout XML files, and have a condition in this block’s .phtml file that excluded any output on category page.
This is a very simple method that simply looks to our Mage registry and asks the question “Is the current page indeed a current category page or not?”.

<?php if(!Mage::registry('current_category')):?>
//OUTPUT THE GLOBAL ELEMENTS CODE ON NONE-CATEGORY PAGES
php endif; ?>
 
 
Simple as that, of course the correct way would be to include this block globally via your XML layout files, and then remove it via XML (Custom Layout Update) in the backend->catalog->manage categories “Custom Design” tab for each category.



============================

Get the current category in Magento

 

I’ve come across several places where I’ve needed to get the current category (or information from it) in one way or another. Some blocks have the ability to do this:
$_category = $this->getCurrentCategory();
However, if you need to get the current category in a block (or model, helper, whichever) where this method isn’t present, then we can simply do this instead:
$_category = Mage::registry('current_category');
They both return exactly the same object (unless overridden, that is Mage_Catalog_Model_Category).
Caveat: If you are in a block that doesn’t have access to ‘getCurrentCategory’ nor is Mage::registry(‘current_category’) defined (for example, the product list being applied to the home/front page) you can load by category ID if known. In this example, the Mage_Catalog_Block_Product_List has been applied to the front page, so you’d need to do this instead:
// Check for $_category's existance/status after initial block load, and grab the category ID from the object's parameters/attributes.
// Replace $this->getCategoryId() with a category ID, whether defined statically or retrieved from another method.
if (!is_object($_category))
     $_category = Mage::getModel('catalog/category')->load($this->getCategoryId());
Of course, this ends up being slightly different depending on where you need to get the category object.

By PHP with No comments

Monday, May 13, 2013

Magento - Advanced Search Category Lists In Select Box

How to Place the Category Lists in advanced Search page., Search by category in magento.

n the advanced search page, “search by category” is not an option by default, but can be very helpful. To add this, you will need to edit the following files:
  • app/code/core/Mage/CatalogSearch/Block/Advanced/Form.php
  • app/code/core/Mage/CatalogSearch/Model/Advanced.php
  • app/design/yourdesign/yourdesign/template/catalogsearch/advanced/form.phtml
At the very end of app/code/core/Mage/CatalogSearch/Block/Advanced/Form.php (before the closing brace), add:
  1.     public function getStoreCategories()
  2.     {
  3.         $helper = Mage::helper('catalog/category');
  4.         return $helper->getStoreCategories();
  5.     }
In app/code/core/Mage/CatalogSearch/Model/Advanced.php, replace the getSearchCriterias() function (line 157) with the code below:
  1. public function getSearchCriterias()
  2.     {
  3.         $search = $this->_searchCriterias;
  4.         /* display category filtering criteria */
  5.         if(isset($_GET['category']) && is_numeric($_GET['category'])) {
  6.             $category = Mage::getModel('catalog/category')->load($_GET['category']);
  7.             $search[] = array('name'=>'Category','value'=>$category->getName());
  8.         }
  9.         return $search;
  10.     }
replace the next function, getProductCollection(), with:
  1.   public function getProductCollection(){
  2.         if (is_null($this->_productCollection)) {
  3.             $this->_productCollection = Mage::getResourceModel('catalogsearch/advanced_collection')
  4.                 ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
  5.                 ->addMinimalPrice()
  6.                 ->addStoreFilter();
  7.                 Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($this->_productCollection);
  8.                 Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($this->_productCollection);
  9.             /* include category filtering */
  10.             if(isset($_GET['category']) && is_numeric($_GET['category'])) $this->_productCollection->addCategoryFilter(Mage::getModel('catalog/category')->load($_GET['category']),true);
  11.         }
  12.  
  13.         return $this->_productCollection;
  14.     }
In app/design/yourdesign/yourdesign/template/catalogsearch/advanced/form.phtml, after this code:
  1.         <?php foreach ($this->getSearchableAttributes() as $_attribute): ?>
  2.         <?php $_code = $_attribute->getAttributeCode() ?>
  3.         <li>
  4.             <label for="<?php echo $_code ?>"><?php echo $this->getAttributeLabel($_attribute) ?></label>
  5.             <?php switch($this->getAttributeInputType($_attribute)):
  6.                 case 'number': ?>
  7.                 <div class="range field-row">
  8.                     <input name="<?php echo $_code ?>[from]" value="<?php echo $this->htmlEscape($this->getAttributeValue($_attribute, 'from')) ?>" id="<?php echo $_code ?>" title="<?php echo $this->htmlEscape($this->getAttributeLabel($_attribute)) ?>"  class="input-text validate-number" type="text" />
  9.                     <input name="<?php echo $_code ?>[to]" value="<?php echo $this->htmlEscape($this->getAttributeValue($_attribute, 'to')) ?>" id="<?php echo $_code ?>_to" title="<?php echo $this->htmlEscape($this->getAttributeLabel($_attribute)) ?>"  class="input-text validate-number" type="text"/>
  10.                 </div>
  11.                 <?php break;
  12.                 case 'select': ?>
  13.                     <?php echo $this->getAttributeSelectElement($_attribute) ?>
  14.                 <?php break;
  15.                 case 'yesno': ?>
  16.                     <?php echo $this->getAttributeYesNoElement($_attribute) ?>
  17.                 <?php break;
  18.                 case 'date': ?>
  19.                     <?php echo $this->getDateInput($_attribute, 'from') ?>
  20.                     -
  21.                     <?php echo $this->getDateInput($_attribute, 'to') ?>
  22.                 <?php break;
  23.                 default: ?>
  24.                 <input name="<?php echo $_code ?>" id="<?php echo $_code ?>" value="<?php echo $this->htmlEscape($this->getAttributeValue($_attribute)) ?>" title="<?php echo $this->htmlEscape($this->getAttributeLabel($_attribute)) ?>"  class="input-text <?php echo $this->getAttributeValidationClass($_attribute) ?>" type="text" />
  25.             <?php endswitch; ?>
  26.         </li>
  27.         <?php endforeach; ?>
add:
  1.  
  2.         <li>
  3.             <label for="category_search_field">Search by Category:</label>
  4.             <select name="category" id="category_search_field">
  5.                 <option value="">-- Any Category --</option>
  6.                 <?php foreach ($this->getStoreCategories() as $_category): ?>
  7.                 <?php if($_category->hasChildren()): ?>
  8.                 <option class="parent-cat" value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName();?></option>
  9.                 <?php foreach ($_category->getChildren() as $subcategory):
  10.                 if($subcategory->getIsActive()) : ?>
  11.                     <option value="<?php echo $subcategory->getId(); ?>"<?php echo ($this->getRequest()->getQuery('category') == $subcategory->getId() ? ' selected="selected"': "") ?>><?php echo $subcategory->getName(); ?></option>
  12.                 <?php endif; endforeach; ?>
  13.                 <?php elseif($_category->getIsActive()): ?>
  14.                 <option value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName();?></option>
  15.                 <?php endif; ?>
  16.                 <?php endforeach ?>
  17.  
  18.             </select>
  19.         </li>
Now, If you are going to search only by Category then you will face an error message like “You have to specify at least one search term”. To solve it you need to modify following file:
  • app/code/core/Mage/CatalogSearch/Model/Advanced.php
Open the file and search this function addFilters. In this function you can see following codes, replace this
  1. if ($allConditions) {
  2.             $this->getProductCollection()->addFieldsToFilter($allConditions);
  3.         } else if (!count($filteredAttributes)) {
  4.             Mage::throwException(Mage::helper('catalogsearch')->__('You have to specify at least one search term'));
  5.         }
with following codes:
  1. if (($allConditions) || (isset($values['category']) && is_numeric($values['category']))) {
  2.             $this->getProductCollection()->addFieldsToFilter($allConditions);
  3.         } else if (!count($filteredAttributes)) {
  4.             Mage::throwException(Mage::helper('catalogsearch')->__('You have to specify at least one search term'));
  5.         }
Now you won’t face any problem in advanced search only by Category or any single attribute search.

By PHP with No comments

    • Popular
    • Categories
    • Archives