Skip to content

Instantly share code, notes, and snippets.

@claudiu-marginean
Last active July 6, 2021 08:54
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save claudiu-marginean/7484308 to your computer and use it in GitHub Desktop.
Save claudiu-marginean/7484308 to your computer and use it in GitHub Desktop.
Magento Snippets - Claudiu

Magento Snippets

Code snippets from different sections of Magento that are very useful.

JS Translation in phtml files

<script>
//<![CDATA[
Translator.add(
    <?php echo Mage::helper('core')->jsonEncode(array(
        'Please use letters only.' => $this->__('Please use letters only.'),
        'Please use letters only.' => $this->helper('jstranslate')->__('Please use letters only.'),           
    )) ?>
);
//]]>
</script>

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') ?>

Encrypt or decrypt using the secret crypt key from local.xml

/usr/local/bin/n98-magerun.phar --skip-root-check dev:console
<?php echo Mage::helper('core')->encrypt('xxxx') ?>
<?php echo Mage::helper('core')->decrypt('xxxx') ?>
<?php echo Mage::helper('core')->decrypt(Mage::getStoreConfig('payment_services/ops/secret_key_in')) ?>

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

Create a new file in /lib/FB.php

<?php

//Use FirePHP for development debug
//TODO - Do not comment the require classes because there might be FB::log() in the source that will stop with errors
require_once('FirePHPCore/FirePHP.class.php');
require_once('FirePHPCore/fb.php');

//TODO Disable debug output in production
//FB::setEnabled(false);

//Export Error, Exception & Assertion Handling using FirePHP
//$firePHP = FirePHP::getInstance(true);
//$firePHP->registerErrorHandler();
//$firePHP->registerExceptionHandler();
//$firePHP->registerAssertionHandler();

Encode Magento Objects in FirePHP lib

Usefull for debug Magneto objects

Changes in file /lib/FirePHPCore/FirePHP.class.php

<?php
protected function encodeObject($Object, $ObjectDepth = 1, $ArrayDepth = 1, $MaxDepth = 1)
{
	if ($MaxDepth > $this->options['maxDepth']) {
		return '** Max Depth ('.$this->options['maxDepth'].') **';
	}
	$return = array();

	//BOF Magento encodeObject for debug
        if (is_object($Object) && $Object instanceof Varien_Object) {
            $class = get_class($Object);
            $Object = $Object->debug();
            $Object['__className'] = $class;
        } elseif (is_object($Object) && $Object instanceof Varien_Data_Collection) {
            $class = get_class($Object);
            $Object = $Object->toArray();
            $Object['__className'] = $class;
        }
	//EOF Magento encodeObject for debug
	
	if (is_resource($Object)) {
		return '** '.(string)$Object.' **';
	}
	// ... the rest of the function

	return $return;	
}
?>

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