Tuesday, July 14, 2015

Early Magento Session Instantiation or PHPSESSID in Magento

While doing security fix in magento we come across one unknown session is getting create which name has php default session PHPSESSID after debugging we come to when customer session is int at that time we are not passing session name so to block PHPSESSID need to add else condition in Mage_Core_Model_Session_Abstract_Varien::start()
 if (!empty($sessionName)) {
            $this->setSessionName($sessionName);
        }else{
   return $this;
  }

else{ return $this; }
got some clue from http://alanstorm.com/magento_sessions_early but as per this block they are doing same change in event level i did it in core abstract file itself

Thursday, May 7, 2015

Magento Grouped Products Containing Associated Configurable Products


for

http://brimllc.com/2010/12/magento-grouped-products-containing-associated-configurable-products/

in group.php add below code

if($subProduct->getTypeId() == 'configurable' ){
      $buyRequestconfig['super_attribute']=$buyRequest['super_attribute'][$subProduct->getId()];
      $buyRequestconfig['product']=$subProduct->getId();
      //$buyRequestconfig['product_id']=$subProduct->getId();
      $buyRequestconfig['qty'] = $buyRequest['super_group'][$subProduct->getId()];
      $buyRequestconfig['form_key'] = $buyRequest['form_key'];
      $buyRequestconfig['uenc'] = $buyRequest['uenc'];
      //$cart = Mage::getModel("checkout/cart");
      //$cart->addProduct($subProduct, $buyRequestconfig); 
      //print_r($buyRequest); exit;
/*        $products[] = $subProduct->getTypeInstance(true)
          ->_prepareProduct(
           $buyRequestconfig,
           $subProduct,
           $processMode
          );
      
 */      
      $subProduct = $subProduct->getTypeInstance(true)->getProductByAttributes($buyRequestconfig['super_attribute'], $subProduct);
       $productsInfo[$subProduct->getId()]=1;
     }

and also in 

configurable.phtml

<?php 
/**
 * This template handles individual configurable products that have been associated with a grouped product.
 */
?>

<?php
$_product    = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
$_formId = "product_addtocart_wrapper_".$_product->getId();
$_formJsVar = "productAddToCartForm".$_product->getId();
?>
<div class="price-box"><?php //echo $this->getPriceHtml($_product); ?></div>
<div id="<?php echo $_formId ?>">

<h3><?php echo $_product->getName() ?></h3>

<div class="no-display">
 <input type="hidden" name="product" value="<?php echo $_product->getId() ?>" />
    <input type="hidden" name="related_product" id="related-products-field" value="" />
</div>

<?php if ($_product->isSaleable() && count($_attributes)):?>
    <dl>
    <?php foreach($_attributes as $_attribute): ?>
        <dt><label><?php echo $_attribute->getLabel() ?><span class="required"> *</span></label></dt>
        <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
          <select name="super_attribute[<?php echo $_product->getId() ?>][<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="go-qty-required-entry  required-entry super-attribute-select">
            <option><?php echo $this->__('Choose an Option...') ?></option>
          </select>
        </dd>
    <?php endforeach; ?>
    </dl>
    <script type="text/javascript">
        var spConfig = new Product.GroupedConfig(<?php echo $this->getJsonConfig() ?>, <?php echo $_product->getId() ?>);
        spConfig.setOptionsPrice(new Product.OptionsPrice(<?php echo Mage::helper('groupedconfigured')->getProductViewJsonConfig($_product) ?>));
    </script>
    <?php echo $this->getPriceHtml($_product) ?>
    
   
    <input id="super_group_<?php echo $_product->getId(); ?>" type="hidden" name="super_group[<?php echo $_product->getId() ?>]" maxlength="12" value="1<?php //echo $_item->getQty()*1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />                            
    <script type="text/javascript">
    //<![CDATA[
            var <?php echo $_formJsVar ?> = new VarienForm('<?php echo $_formId ?>');
            <?php echo $_formJsVar ?>.submit = function(){
                    if (this.validator.validate()) {
                            this.form.submit();
                    }
            }.bind(<?php echo $_formJsVar ?>);
    //]]>
    </script>
<?php endif;?>
</div>


which will support magento1.9

Monday, April 13, 2015

Concatenate two fields in admin grid with filter in magento

i override Mage/Adminhtml/Block/Sales/Order/Grid.php to local and You can use this technique for any Magento core file. This way, you can avoid overriding the core file. This way, you can also avoid the risk of over writing your custom code by the system during the Magento system upgrade operation. Now, go for the main action. Open the Grid.php file from its new local directory and look at the following block of code carefully:
protected function _getCollectionClass()
{
    return 'sales/order_grid_collection';
}
 
protected function _prepareCollection()
{
    $collection = Mage::getResourceModel($this->_getCollectionClass());
    /* adding customer name section */       
$customerFirstNameAttr = Mage::getSingleton('customer/customer')->getResource()->getAttribute('firstname');
$customerLastNameAttr = Mage::getSingleton('customer/customer')->getResource()->getAttribute('lastname');
$collection->getSelect()
                    ->joinLeft(
                        array('cusFirstnameTb' => $customerFirstNameAttr->getBackend()->getTable()),
                        'main_table.customer_id = cusFirstnameTb.entity_id AND cusFirstnameTb.attribute_id = '.$customerFirstNameAttr->getId(). ' AND cusFirstnameTb.entity_type_id = '.Mage::getSingleton('customer/customer')->getResource()->getTypeId(),
                        array('cusFirstnameTb.value')
                    );   
     
$collection->getSelect()
                    ->joinLeft(
                        array('cusLastnameTb' => $customerLastNameAttr->getBackend()->getTable()),
                        'main_table.customer_id = cusLastnameTb.entity_id AND cusLastnameTb.attribute_id = '.$customerLastNameAttr->getId(). ' AND cusLastnameTb.entity_type_id = '.Mage::getSingleton('customer/customer')->getResource()->getTypeId(),
                        array('customer_name' => "CONCAT(cusFirstnameTb.value, ' ', cusLastnameTb.value)")
                    ); 
    /* end adding customer name section */ 
    $this->setCollection($collection);
    return parent::_prepareCollection();
}
Now take a deep look at the following portion from the above code section. You’ll understand that this following section is the newly added custom code:
/* adding customer name section */       
    $customerFirstNameAttr = Mage::getSingleton('customer/customer')->getResource()->getAttribute('firstname');
    $customerLastNameAttr = Mage::getSingleton('customer/customer')->getResource()->getAttribute('lastname');
    $collection->getSelect()
                        ->joinLeft(
                            array('cusFirstnameTb' => $customerFirstNameAttr->getBackend()->getTable()),
                            'main_table.customer_id = cusFirstnameTb.entity_id AND cusFirstnameTb.attribute_id = '.$customerFirstNameAttr->getId(). ' AND cusFirstnameTb.entity_type_id = '.Mage::getSingleton('customer/customer')->getResource()->getTypeId(),
                            array('cusFirstnameTb.value')
                        );   
         
    $collection->getSelect()
                        ->joinLeft(
                            array('cusLastnameTb' => $customerLastNameAttr->getBackend()->getTable()),
                            'main_table.customer_id = cusLastnameTb.entity_id AND cusLastnameTb.attribute_id = '.$customerLastNameAttr->getId(). ' AND cusLastnameTb.entity_type_id = '.Mage::getSingleton('customer/customer')->getResource()->getTypeId(),
                            array('customer_name' => "CONCAT(cusFirstnameTb.value, ' ', cusLastnameTb.value)")
                        ); 
/* end adding customer name section */ 
in the admin sales order grid with the name “customer_name” by inserting the following code snippet in the _prepareColumns() method of the Mage_Adminhtml_Block_Sales_Order_Grid class :
$this->addColumn('customer_name', array(
    'header'    => Mage::helper('adminhtml')->__('Customer Name'),
    'index'     => 'customer_name',
    'filter_condition_callback' => array($this, 'customerNameFilter'),
    'width'     => '120px',
)); 
public function customerNameFilter($collection, $column){
    $filterValue = $column->getFilter()->getValue();
    if(!is_null($filterValue)){
        $filterValue = trim($filterValue);
        $filterValue = preg_replace('/[\s]+/', ' ', $filterValue);
 
        $whereArr = array();
        $whereArr[] = $collection->getConnection()->quoteInto("cusFirstnameTb.value = ?", $filterValue);
        $whereArr[] = $collection->getConnection()->quoteInto("cusLastnameTb.value = ?", $filterValue);
        $whereArr[] = $collection->getConnection()->quoteInto("CONCAT(cusFirstnameTb.value, ' ', cusLastnameTb.value) = ?", $filterValue);
        $where = implode(' OR ', $whereArr);
        $collection->getSelect()->where($where);
    }
}

Thursday, February 5, 2015

Magento Auto Login and Auto Authorize for Rest API

We can skip login and authorize page when your doing rest api call in magento we can just make it admin login and create the token by using that token and secret key we can access need rest api for more information you can contact me pradeep.kumarrcs67@gmail.com +91-9916038230

Sunday, November 10, 2013

Remove the products from category products and update or map new product to category in magento programmatically

In some time you need to remove all the products from category or unset all products from category and add or update new product to category at that time you use below code for ex:- you need to run cron job which will run every day and get a product collection of sale attribute and map that products to that category
<?php
    set_time_limit(0); 
    define('MAGENTO', '..');
    require_once MAGENTO . '/app/Mage.php';
    Mage::app();

    //Load product model collecttion filtered by sale attribute
     $proCollection = Mage::getModel('catalog/product')
                        ->getCollection()
                        ->addAttributeToSelect(array('entity_id'))
                        ->addAttributeToFilter('sale', '1');
                         
    
$writeConnection = Mage::getSingleton('core/resource')->getConnection('core_write');

        // Delete Existing Mapped product from Sale Category
        $catId=722;
        $delQuery = 'Delete from catalog_category_product where category_id ='.$catId;
        $writeConnection->query($delQuery);
        $category=Mage::getModel('catalog/category')->load($catId);
        $products = array();
        $category_products='';
        foreach ($proCollection as $product){
            if(!$category_products){
                $category_products=$product->getId().'=1&';
            }else{
                $category_products .=$product->getId().'=1&';            
            }        
        }
        //$data['category_products']='4867=1&4868;=1&4876;=1';
        parse_str($category_products, $products);    
        $category->setPostedProducts($products)->save();
        
    
        $process = Mage::getModel('index/indexer')->getProcessByCode('catalog_category_product');
        $process->reindexAll();
        
        echo 'successfully mapped the data<br>';
        exit;

?>
Download file setSale.php
http://www.magentocommerce.com/boards/viewthread/704216/

Get Todays start and end date with time in Magento

Some time we need to get collection of report or product collection of today date ,at that time need to set start date from 00:00:00 time and end with 23:59:59 for that use below code
 $todayStartOfDayDate      = Mage::app()->getLocale()->date()->setTime('00:00:00')->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
    $todayEndOfDayDate      = Mage::app()->getLocale()->date()->setTime('23:59:59')->toString(Varien_Date::DATETIME_INTERNAL_FORMAT); 
or eg:- newarrival of product collection;
 $proCollection = Mage::getModel('catalog/product')
                        ->getCollection()
                        ->addAttributeToSelect(array('entity_id'))
                        ->addAttributeToFilter('news_from_date', array('or'=> array(
                                    0 => array('date' => true, 'to' => $todayEndOfDayDate),
                                    1 => array('is' => new Zend_Db_Expr('null')))
                                ), 'left')
                                ->addAttributeToFilter('news_to_date', array('or'=> array(
                                    0 => array('date' => true, 'from' => $todayStartOfDayDate),
                                    1 => array('is' => new Zend_Db_Expr('null')))
                                ), 'left')
                                ->addAttributeToFilter(
                                    array(
                                        array('attribute' => 'news_from_date', 'is'=>new Zend_Db_Expr('not null')),
                                        array('attribute' => 'news_to_date', 'is'=>new Zend_Db_Expr('not null'))
                                        )
                                 ); 
http://www.magentocommerce.com/boards/viewthread/704170/

Friday, November 8, 2013

Cache a particular block or html in Magento

Hi, we can cache the block and also we can cache the particular HTML block code 1st time it will cache and from next time it will call from cache for eg:- in product view page your list a information in for each loop so each time it will kill your performance so 1st time cache and next time load it from cache we can cache in 2 ways 1. Cache a Block in block php add below code ex List.php
 public function __construct()
    {
        $this->addData(array(
            'cache_lifetime'    => 1800,
            'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG),
            'cache_key'         => $this->getCacheKey()
        ));
    } 

    public function getCacheKey()
    {
        return $this->getRequest()->getRequestUri().$this->getCacheCurrencyCode();
    }

    //retreive current currency code
    public function getCacheCurrencyCode()
    {
        return Mage::app()->getStore()->getCurrentCurrencyCode();
    } 
2. cache a particular html block (only html code will cache it will not cache any objects ) you can do below logic even by creating new block file and can call it in product view page if you dont want to create new block for this small things you can cache the information
 <?php 
$cache = Mage::getSingleton('core/cache');
$cacheTag    = array(
Mage_Catalog_Model_Product::CACHE_TAG,
);
$currentCurrencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
$storeId = Mage::app()->getStore()->getId();
$plantationkey=str_replace(' ', '_', $plantation);
$cacheKey    = 'Origin_' .$plantationkey . $storeId .$currentCurrencyCode;
$orginhtml = $cache->load($cacheKey);

if(!empty($orginhtml)){
    echo $orginhtml;
}else{
    $theProductBlock = new Mage_Catalog_Block_Product;
    $Bestsellerproducts = Mage::getResourceModel('catalog/product_collection')
                    ->addAttributeToSelect('*')
                    ->addFieldToFilter(array(array('attribute'=>'bestseller','in'=>1)))
                    ->addAttributeToFilter('visibility', $this->visibility)
                    ->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
                    ->addCategoryFilter($category); ?>

    <?php if(count($Bestsellerproducts)):?>
    <?php 
    $orginhtml ='<ul>';
    foreach($Bestsellerproducts as $bestseller){ 
    $orginhtml .='<li>
        <h2>'.$bestseller->getName().'</h2>
        <a href="'.$bestseller->getProductUrl().'" class="product-img"><img src="'.$this->helper('catalog/image')->init($bestseller, 'small_image')->resize(229).'" width="229" height="229" alt="'.$this->stripTags($this->getImageLabel($bestseller, 'small_image'), null, true).'" title="'.$bestseller->getName().'" /></a>
        <h2 class="product-name"><a href="'.$bestseller->getProductUrl().'">'.$bestseller->getName().'</a>
        </li>';
    }
 endif; ?>    


<?php echo $orginhtml; ?>
<?php $cache->save($orginhtml, $cacheKey, $cacheTag, 3600); ?>
<?php }    ?> 
http://www.magentocommerce.com/boards/viewthread/700444/