Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mukundthanki/4b1ec103cfe6a135857a to your computer and use it in GitHub Desktop.
Save mukundthanki/4b1ec103cfe6a135857a to your computer and use it in GitHub Desktop.

Magento Snippets

Simulate and test AJAX fail() actions in Mangeto

<?php
public function testAction()
{
        $this->getResponse()
            ->setHeader('HTTP/1.1', '403 Session Expired')
            ->setHeader('Login-Required', 'true')
            ->sendResponse();
        return;
}
?>

Get crypt key from local.xml

<?php echo (string) Mage::getConfig()->getNode('global/crypt/key') ?>

Debug Module load order

<?php 
//In \Mage_Core_Model_Config::getNode on line 319
FB::log(array_keys($this->getNode('modules')->asArray()));
?>

Test if a module is enable

<?php Mage::helper('core')->isModuleEnabled('Mage_Review'); ?>

Get specific installer object any place in the code

<?php 
/* @var $installer Mage_Eav_Model_Entity_Setup */
$installer = Mage::getSingleton('eav/entity_setup', 'core_setup');
?>

Include FirePHP debug into Magento

Copy lib files from http://www.firephp.org/ into /lib/FirePHPCore/FirePHP.class.php

Add lines in /index.php

<?php


require_once $mageFilename;

if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
    //Activate errors and developer mode
    Varien_Profiler::enable();
    Mage::setIsDeveloperMode(true);
    ini_set('display_errors', 1);
}

//Use FirePHP for development debug
require_once('FirePHPCore/FirePHP.class.php');
require_once('FirePHPCore/fb.php');

if (!isset($_SERVER['FIREPHP_DEVELOPER_MODE'])) {
    //disable debug output in production
    FB::setEnabled(false);
}

...

?>

Chenge from dropdown into multiple select

UPDATE eav_attribute SET 
backend_model = 'eav/entity_attribute_backend_array',
frontend_input = 'multiselect',
backend_type = 'varchar',
source_model = NULL
WHERE attribute_id = {{attribute_id}};

INSERT INTO catalog_product_entity_varchar (entity_type_id, attribute_id, store_id, entity_id, value)
SELECT entity_type_id, attribute_id, store_id, entity_id, value FROM catalog_product_entity_int WHERE attribute_id = {{attribute_id}};

DELETE FROM catalog_product_entity_int WHERE attribute_id = {{attribute_id}};

Include controller files

<?php require_once Mage::getModuleDir('controllers', 'Mage_Checkout') . DS . 'CartController.php'; ?>

Get a list of handles of your controller

<?php Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles()); ?>

Verify if a module is active or not

<?php Mage::getConfig()->getModuleConfig('Mage_Persistent')->is('active'); ?>

Overwrite a join that was executed before

<?php 
  /* @var $session Mage_Customer_Model_Session */
  $session = Mage::getSingleton('customer/session');
  /* @var $collection Enterprise_GiftRegistry_Model_Resource_Entity_Collection */
  $collection = Mage::getModel('enterprise_giftregistry/entity')->getCollection();
  $collection->addFieldToFilter('customer_id', $session->getCustomerId());
  $collection->addRegistryInfo();
  $collection->addFieldToSelect('*');
  
  /**
   * Add items count for each enterprise_giftregistry entity
   * - Recreate Select and Join query from Enterprise_GiftRegistry_Model_Resource_Entity_Collection::_addQtyItemsData
   *
   * @see Enterprise_GiftRegistry_Model_Resource_Entity_Collection::_addQtyItemsData
   */
  $select = $collection->getConnection()->select()
      ->from(array('item' => $collection->getTable('enterprise_giftregistry/item')), array(
          'entity_id',
          'items_count'   => new Zend_Db_Expr('COUNT(*)'),
          'qty'           => new Zend_Db_Expr('SUM(item.qty)'),
          'qty_fulfilled' => new Zend_Db_Expr('SUM(item.qty_fulfilled)'),
          'qty_remaining' => new Zend_Db_Expr('SUM(item.qty - item.qty_fulfilled)')
      ))
      ->group('entity_id');
  $helper = Mage::getResourceHelper('core');
  $query = $helper->getQueryUsingAnalyticFunction($select);
  
  //unset joinLeft executed before
  $from = $collection->getSelect()->getPart(Zend_Db_Select::FROM);
  unset($from['items']);
  $collection->getSelect()->setPart(Zend_Db_Select::FROM, $from);
  
  $collection->getSelect()->joinLeft(
      array('items' => new Zend_Db_Expr(sprintf('(%s)', $query))),
      'main_table.entity_id = items.entity_id',
      array('items_count')
      //'qty', 'qty_fulfilled', 'qty_remaining' - this are already in columns part
  );
  //var_dump('SQL:'.$collection->getSelect());
?>

Other code that need to be refine

//Get a list of handles of your controller
Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles());

        
$specialPriceToId = Mage::getSingleton('eav/entity_attribute')->getIdByCode(Mage_Catalog_Model_Product::ENTITY, 'special_to_date');

$price_attribute = Mage::getModel('eav/entity')->setType(Mage_Catalog_Model_Product::ENTITY)->getAttribute('price');
$price_attribute = Mage::getModel('eav/entity')->setType('catalog_product')->getAttribute('price');

$attribute = Mage::getSingleton('eav/config')->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
	
//Line of code that let you know if you are in admin panel 
Mage::getDesign()->getArea() == 'adminhtml'

//Developer Client Restrictions:
//filter request based on Allowed IPs (comma separated)
Mage::helper('core')->isDevAllowed()


Mage::app()->getCacheInstance()

//Get block class in observer code:
$block = Mage::app()->getFrontController()->getAction()->getLayout()->getBlock('google_analytics');

//trigger reindex price on product id (NOT TESTED)
Mage::getSingleton('index/indexer')->processEntityAction(
	new Varien_Object(array('id' => $productId)),
	Mage_Catalog_Model_Product::ENTITY,
	Mage_Catalog_Model_Product_Indexer_Price::EVENT_TYPE_REINDEX_PRICE
);


//trigger reindex price on product id (TESTED by Mihai)
$productIds = array('27','28');
Mage::getResourceSingleton('catalog/product_indexer_price')->reindexProductIds($productIds);

//trigger reindex price on product id (NOT TESTED)
Mage::getResourceSingleton('cataloginventory/indexer_stock')->reindexProducts($productIds);

//import controller file
require_once  Mage::getModuleDir('controllers','Mage_Newsletter').DS.'SubscriberController.php'; 



Varien_Profiler::start('TEST_1');
// your code here to test
Varien_Profiler::stop('TEST_1');
echo '<br /><br />TEST_1 -> Execution time: '.number_format(Varien_Profiler::fetch('TEST_1', 'sum'),3).' sec';

try{
	
} catch (Exception $e) {
	Mage::logException($e);
}


try{

	Mage::throwException('ERROR MESSAGE');
	Mage::throwException(Mage::helper('core')->__('Error Message ...'));
	
} catch (Exception $e) {

	Mage::log("ERROR:".$e->getMessage()."/nTrace: ".$e->getTraceAsString(), Zend_Log::ERR ,'dev.log', true);	
	Mage::logException($e);
	
	
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment