⭐ If you would like to buy me a coffee, well thank you very much that is mega kind! : https://www.buymeacoffee.com/honeyvig Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies
Showing posts with label Magento Tips & Tricks. Show all posts
Showing posts with label Magento Tips & Tricks. Show all posts

Monday, July 8, 2013

Disable state/province option in the Magento

Sometime your Magento site doesn’t need the region/state for customer address and you don’t know how to turn it off without touching in many places in the complex Magento source code. Please try to run following SQL statements to try
1
2
update core_config_data set `value`=0 where path = 'general/region/display_all';
update core_config_data set `value`='' where path = 'general/region/state_required';
Checked on: Magento 1.7.0.2

Friday, July 5, 2013

How to add a custom button to an Admin page: Magento EE 1.12.0.2

I needed a custom button to call a url. I wanted this button to appear above my grid in Admin>Sales>Orders.
This proved to be simple once I learned how the Admin grid pages are organized. There are two elements to each page: the container for the grid and the grid itself. In my other post about adding a “Download” status, I had to add “Download” to the drop-down menu in the grid itself. For this button at the top of the page, I needed to find the container for the Order Grid.
This code adds a button which says “Download” to the right of the + Create New Order button. When clicked, the Download button calls a URL (which in my case triggers a php script to do some database operations.)
Find this file:
/app/code/core/Mage/Adminhtml/Block/Sales/Order.php
This is the container for the grid which shows the order.
Copy that file and place it here:
/app/code/local/Mage/Adminhtml/Block/Sales/Order.php
This will override the original without changing the original. (You don’t want to change the original files, but override them with custom files.)
Now, open the custom file you just placed in your custom directory, and edit it so that there is new code for the button inside the __construct() function. Here is an example of the whole function with the new button code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public function __construct()
   {
       $this->_controller = 'sales_order';
       $this->_headerText = Mage::helper('sales')->__('Orders');
       $this->_addButtonLabel = Mage::helper('sales')->__('Create New Order');
         
         
       ///////CUSTOM code for new button:
       $data = array(
               'label' =>  'Download to Mas',
               'onclick'   => "setLocation('".$this->getUrl('downloadtomas')."')"
               );
       ///////The URL I am using is a custom module that I set up earlier, Magento parses it to <MySite.com/shop/index.php/downloadtomas>, which then runs the script I have in the IndexController.php file
       Mage_Adminhtml_Block_Widget_Container::addButton('download_to_mas', $data, 0, 100,  'header', 'header');
       ///////End CUSTOM code
         
         
       parent::__construct();
       if (!Mage::getSingleton('admin/session')->isAllowed('sales/order/actions/create')) {
           $this->_removeButton('add');
       }
   }

Wednesday, July 3, 2013

Magento Resetting File Permissions

Here’s how to reset your file and directory permissions if PHP is running through FastCGI, suPHP, or LSAPI:
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod 550 pear
chmod 550 mage #for magento 1.5+
If PHP is running as a module (DSO), you will need to do this:
#for magento 1.5+
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod o+w var var/.htaccess app/etc
chmod 550 mage
chmod -R o+w media
If you are running Pre 1.5 you can copy and paste this
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod o+w var var/.htaccess app/etc
chmod 550 pear
chmod -R o+w media
The above commands need to be executed from the root directory where Magento is installed.
Note that the wiki software on this site seems to have some sort of double escaping issue that keeps removing the backslash before ; at the end of the ‘find . -type …’ lines. Every time you edit this page, you’ll have to restore them by making sure there are three slashes before each semicolon that should have a backslash before it! See http://www.linuxquestions.org/questions/linux-newbie-8/find-missing-argument-to-%60-exec-308111/ for details.
If you do not have access to SSH:
Download Magento Cleanup Tool
Unzip magento-cleanup.php to the root directory where Magento is installed.
Browse to http://yourdomain.com/magento/magento-cleanup.php
!!! In Magento Version 1.5. you need to change magento-cleanup.php:
Edit:
chmod(“pear”, 550);
Into:
chmod(“lib/PEAR”, 550);
[Added by Pedro Machado on 2011/07/05] I got errors with the SSH option above, so you may need like me to cleanup session and cache folders:
rm -rf var/cache/*
rm -rf var/session/*
And set the var folder to 755:
chmod 755 -R var

Tuesday, July 2, 2013

Custom Module with Custom Database Table

Document Conventions
I am going to use a few common conventions here that should make it easier to figure out what you need to replace as I am making this as generic as possible.
Anything in angled brackets (including the angled brackets): , needs to replaced with the appropriate text..
Anything in square brackets (including the square brackets): [ ], needs to replaced with the appropriate text.
The reason I am using two different conventions here are that XML files already use angled brackets so you will only see the square brackets in use in XML files.
NOTE: All directory, file, class names are Case Sensitive unless otherwise noted.
Create Directories
Magento Modules follow a common naming scheme, Namespace_Module. This is very important to remember as you need to be careful about how you name your classes. Every custom module will be created in the directory:
/app/code/local
The first step in creating your custom module is determining the namespace and module name. The namespace is simply an extra division that you can create you module in. This means that you can have two modules named the same thing if they are in two different namespaces. One way to use namespaces is to use your company name or initials for all of your modules. If my company name is Acme and I am creating a module called News the full module name would be Acme_News. Magento uses the namespace Mage. There is nothing stopping you from using that namespace under local, i.e. you could create Mage_News and that would work just fine.
Note : You can not use underscore within your module name
Note2: It seems that currently, if you use upper case characters in module names (expecting to show word starts since neither – nor _ is allowed)… the install will fail or rather the module will not work. Suggestion: use a single upper case character, at the beginning of the name.
Let’s setup our directory structure:
/app/code/local///
Block/
controllers/
etc/
Model/
Mysql4/
/
sql/
_setup/
/app/design/frontend///
template/
/
Activate Module
Magento requires there to be an XML file that tells Magento to look for and use your custom module.
/app/etc/modules/_.xml
true
local
Also you can disable your module in the Configuration menu on the backend via the Advanced tab.
NOTE: Due to a bug in Magento, whitespace is not treated correctly. This means that if you leave space in the values between node names (anything in angled brackets is a node), Magento will break.
As an explanation of the above code you will see that all you are changing is the [Namespace]_[Module] text and leaving everything else the same. Please note the capital P in codePool. If this is lowercase this module will not be active.
Create Controller
/app/code/local///controllers/IndexController.php
<?php
class __IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
}
}
NOTE: You may notice that there is no closing, ?>, PHP tag in the code. This is a common coding style that Magento core classes use. Magento Coding Standard is similar (with some exceptions) to Zend Framework PHP Coding Standard and you can find the detailed explanations of this rule in Zend Framework Documentation
Create Configuration XML
/app/code/local///etc/config.xml
0.1.0
standard
[Namespace]_[Module]
[module]
[module].xml
[Namespace]_[Module]_Model
[module]_mysql4
[Namespace]_[Module]_Model_Mysql4
[module]
[Namespace]_[Module]
core_setup
core_write
core_read
[Namespace]_[Module]_Block
[Namespace]_[Module]_Helper
NB : You can use the frontName of your choice without any link to your module name. IE : Mage_Catalog could have “mycatalog” as a frontName.
Create Helper
/app/code/local///Helper/Data.php
<?php
class __Helper_Data extends Mage_Core_Helper_Abstract
{
}
Create Models
If you are quite new to Magento you should pay attention to one of its specifics! The Constructors below are not the usual PHP-Constructors!! Keeping that in mind can save hours of frustrating crashes ;)
/app/code/local///Model/.php
<?php
class __Model_ extends Mage_Core_Model_Abstract
{
public function _construct()
{
parent::_construct();
$this->_init(‘/’);
}
}
/app/code/local///Model/Mysql4/.php
<?php
class __Model_Mysql4_ extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init(‘/’, ‘_id’);
}
}
NOTE: The ‘_id’ refers to the PRIMARY KEY in your database table.
/app/code/local///Model/Mysql4//Collection.php
<?php
class __Model_Mysql4__Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
public function _construct()
{
//parent::__construct();
$this->_init(‘/’);
}
}
SQL Setup
/app/code/local///sql/_setup/mysql4-install-0.1.0.php
startSetup();
$installer->run(”
— DROP TABLE IF EXISTS {$this->getTable(”)};
CREATE TABLE {$this->getTable(”)} (
`_id` int(11) unsigned NOT NULL auto_increment,
`title` varchar(255) NOT NULL default ”,
`content` text NOT NULL default ”,
`status` smallint(6) NOT NULL default ’0′,
`created_time` datetime NULL,
`update_time` datetime NULL,
PRIMARY KEY (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
“);
$installer->endSetup();
NOTE: Please note the text that needs to be replaced. This SQL structure is up to you, this is merely a starting point.
Note Important: If you add fields and couldn’t save data in these fields please try to go to System→Cache Management Then 1.Flush Cache Storage 2.Flush Magento Cache.
Template Design
/app/design/frontend///layout/.xml
NOTE: The block type will automatically figure out what template file to use based on the second [module] declaration.
As an alternate way of declaring what template file to use you can use this: /app/design/frontend///layout/.xml
/app/design/frontend///template//.phtml

__(‘Module List’) ?>

<?php
/*
This will load one record from your database table.
load(_id) will load whatever ID number you give it.
*/
/*
$news = Mage::getModel(‘/’)->load(1);
echo $news->getId();
echo $news->getTitle();
echo $news->getContent();
echo $news->getStatus();
*/
/*
This block of code loads all of the records in the database table.
It will iterate through the collection and the first thing it will do
is set the Title to the current value of $i which is incremented each
iteration and then echo that value back out. At the very end it will
save the entire collection.
*/
/*
$i = 0;
$collection = Mage::getModel(‘/’)->getCollection();
$collection->setPageSize(5);
$collection->setCurPage(2);
$size = $collection->getSize();
$cnt = count($collection);
foreach ($collection as $item) {
$i = $i+1;
$item->setTitle($i);
echo $item->getTitle();
}
$collection->walk(‘save’);
*/
/*
This shows how to load one value, change something and save it.
*/
/*
$object = Mage::getModel(‘/’)->load(1);
$object->setTitle(‘This is a changed title’);
$object->save();
*/
?>
NOTE: Uncomment anything that you would like to use and this is just a starting point and some common methods for you to try and pull the data out.
In this section I am utilizing the built-in Grid Widgets and form capabilities to create a form to allow editing and creating new items for your custom database.
Directory Additions
Here is the revised directory setup due to the additions and changes we need for the backend module.
/app/code/local///
Block/
Adminhtml/
/
Edit/
Tab/
controllers/
Adminhtml/
etc/
Helper/
Model/
Mysql4/
/
sql/
_setup/
Blocks
These control the setup and appearance of your grids and the options that they display.
NOTE: Please note the fact that Block comes before Adminhtml in the class declaration. In any of the Magento modules in Adminhtml it is the opposite. For your module to work it has to be Block_Adminhtml otherwise you will get a ‘Cannot redeclare module…’ error.
/app/code/local///Block/Adminhtml/.php
<?php
class __Block_Adminhtml_ extends Mage_Adminhtml_Block_Widget_Grid_Container
{
public function __construct()
{
$this->_controller = ‘adminhtml_’;
$this->_blockGroup = ”;
$this->_headerText = Mage::helper(”)->__(‘Item Manager’);
$this->_addButtonLabel = Mage::helper(”)->__(‘Add Item’);
parent::__construct();
}
}
/app/code/local///Block/Adminhtml//Edit.php
<?php
class __Block_Adminhtml__Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
public function __construct()
{
parent::__construct();
$this->_objectId = ‘id’;
$this->_blockGroup = ”;
$this->_controller = ‘adminhtml_’;
$this->_updateButton(‘save’, ‘label’, Mage::helper(”)->__(‘Save Item’));
$this->_updateButton(‘delete’, ‘label’, Mage::helper(”)->__(‘Delete Item’));
}
public function getHeaderText()
{
if( Mage::registry(‘_data’) && Mage::registry(‘_data’)->getId() ) {
return Mage::helper(”)->__(“Edit Item ‘%s’”, $this->htmlEscape(Mage::registry(‘_data’)->getTitle()));
} else {
return Mage::helper(”)->__(‘Add Item’);
}
}
}
/app/code/local///Block/Adminhtml//Grid.php
<?php
class __Block_Adminhtml__Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId(‘Grid’);
// This is the primary key of the database
$this->setDefaultSort(‘_id’);
$this->setDefaultDir(‘ASC’);
$this->setSaveParametersInSession(true);
$this->setUseAjax(true);
}
protected function _prepareCollection()
{
$collection = Mage::getModel(‘/’)->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn(‘_id’, array(
‘header’ => Mage::helper(”)->__(‘ID’),
‘align’ =>’right’,
‘width’ => ’50px’,
‘index’ => ‘_id’,
));
$this->addColumn(‘title’, array(
‘header’ => Mage::helper(”)->__(‘Title’),
‘align’ =>’left’,
‘index’ => ‘title’,
));
/*
$this->addColumn(‘content’, array(
‘header’ => Mage::helper(”)->__(‘Item Content’),
‘width’ => ’150px’,
‘index’ => ‘content’,
));
*/
$this->addColumn(‘created_time’, array(
‘header’ => Mage::helper(”)->__(‘Creation Time’),
‘align’ => ‘left’,
‘width’ => ’120px’,
‘type’ => ‘date’,
‘default’ => ‘–’,
‘index’ => ‘created_time’,
));
$this->addColumn(‘update_time’, array(
‘header’ => Mage::helper(”)->__(‘Update Time’),
‘align’ => ‘left’,
‘width’ => ’120px’,
‘type’ => ‘date’,
‘default’ => ‘–’,
‘index’ => ‘update_time’,
));
$this->addColumn(‘status’, array(
‘header’ => Mage::helper(”)->__(‘Status’),
‘align’ => ‘left’,
‘width’ => ’80px’,
‘index’ => ‘status’,
‘type’ => ‘options’,
‘options’ => array(
1 => ‘Active’,
0 => ‘Inactive’,
),
));
return parent::_prepareColumns();
}
public function getRowUrl($row)
{
return $this->getUrl(‘*/*/edit’, array(‘id’ => $row->getId()));
}
public function getGridUrl()
{
return $this->getUrl(‘*/*/grid’, array(‘_current’=>true));
}
}
/app/code/local///Block/Adminhtml//Edit/Form.php
<?php
class __Block_Adminhtml__Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
‘id’ => ‘edit_form’,
‘action’ => $this->getUrl(‘*/*/save’, array(‘id’ => $this->getRequest()->getParam(‘id’))),
‘method’ => ‘post’,
)
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
/app/code/local///Block/Adminhtml//Edit/Tabs.php
<?php
class __Block_Adminhtml__Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
parent::__construct();
$this->setId(‘_tabs’);
$this->setDestElementId(‘edit_form’);
$this->setTitle(Mage::helper(”)->__(‘News Information’));
}
protected function _beforeToHtml()
{
$this->addTab(‘form_section’, array(
‘label’ => Mage::helper(”)->__(‘Item Information’),
‘title’ => Mage::helper(”)->__(‘Item Information’),
‘content’ => $this->getLayout()->createBlock(‘/adminhtml__edit_tab_form’)->toHtml(),
));
return parent::_beforeToHtml();
}
}
/app/code/local///Block/Adminhtml//Edit/Tab/Form.php
<?php
class __Block_Adminhtml__Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset(‘_form’, array(‘legend’=>Mage::helper(”)->__(‘Item information’)));
$fieldset->addField(‘title’, ‘text’, array(
‘label’ => Mage::helper(”)->__(‘Title’),
‘class’ => ‘required-entry’,
‘required’ => true,
‘name’ => ‘title’,
));
$fieldset->addField(‘status’, ‘select’, array(
‘label’ => Mage::helper(”)->__(‘Status’),
‘name’ => ‘status’,
‘values’ => array(
array(
‘value’ => 1,
‘label’ => Mage::helper(”)->__(‘Active’),
),
array(
‘value’ => 0,
‘label’ => Mage::helper(”)->__(‘Inactive’),
),
),
));
$fieldset->addField(‘content’, ‘editor’, array(
‘name’ => ‘content’,
‘label’ => Mage::helper(”)->__(‘Content’),
‘title’ => Mage::helper(”)->__(‘Content’),
‘style’ => ‘width:98%; height:400px;’,
‘wysiwyg’ => false,
‘required’ => true,
));
if ( Mage::getSingleton(‘adminhtml/session’)->getData() )
{
$form->setValues(Mage::getSingleton(‘adminhtml/session’)->getData());
Mage::getSingleton(‘adminhtml/session’)->setData(null);
} elseif ( Mage::registry(‘_data’) ) {
$form->setValues(Mage::registry(‘_data’)->getData());
}
return parent::_prepareForm();
}
}
Controller
/app/code/local///controllers/Adminhtml/Controller.php
NOTE: you need to manually add line 16, which is currently missing in this file. As per suggestion from mkd at page http://www.magentocommerce.com/boards/viewthread/11228/
<?php
class __Adminhtml_Controller extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
$this->loadLayout()
->_setActiveMenu(‘/items’)
->_addBreadcrumb(Mage::helper(‘adminhtml’)->__(‘Items Manager’), Mage::helper(‘adminhtml’)->__(‘Item Manager’));
return $this;
}
public function indexAction() {
$this->_initAction();
$this->_addContent($this->getLayout()->createBlock(‘/adminhtml_’));
$this->renderLayout();
}
public function editAction()
{
$Id = $this->getRequest()->getParam(‘id’);
$Model = Mage::getModel(‘/’)->load($Id);
if ($Model->getId() || $Id == 0) {
Mage::register(‘_data’, $Model);
$this->loadLayout();
$this->_setActiveMenu(‘/items’);
$this->_addBreadcrumb(Mage::helper(‘adminhtml’)->__(‘Item Manager’), Mage::helper(‘adminhtml’)->__(‘Item Manager’));
$this->_addBreadcrumb(Mage::helper(‘adminhtml’)->__(‘Item News’), Mage::helper(‘adminhtml’)->__(‘Item News’));
$this->getLayout()->getBlock(‘head’)->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock(‘/adminhtml__edit’))
->_addLeft($this->getLayout()->createBlock(‘/adminhtml__edit_tabs’));
$this->renderLayout();
} else {
Mage::getSingleton(‘adminhtml/session’)->addError(Mage::helper(”)->__(‘Item does not exist’));
$this->_redirect(‘*/*/’);
}
}
public function newAction()
{
$this->_forward(‘edit’);
}
public function saveAction()
{
if ( $this->getRequest()->getPost() ) {
try {
$postData = $this->getRequest()->getPost();
$Model = Mage::getModel(‘/’);
$Model->setId($this->getRequest()->getParam(‘id’))
->setTitle($postData['title'])
->setContent($postData['content'])
->setStatus($postData['status'])
->save();
Mage::getSingleton(‘adminhtml/session’)->addSuccess(Mage::helper(‘adminhtml’)->__(‘Item was successfully saved’));
Mage::getSingleton(‘adminhtml/session’)->setData(false);
$this->_redirect(‘*/*/’);
return;
} catch (Exception $e) {
Mage::getSingleton(‘adminhtml/session’)->addError($e->getMessage());
Mage::getSingleton(‘adminhtml/session’)->setData($this->getRequest()->getPost());
$this->_redirect(‘*/*/edit’, array(‘id’ => $this->getRequest()->getParam(‘id’)));
return;
}
}
$this->_redirect(‘*/*/’);
}
public function deleteAction()
{
if( $this->getRequest()->getParam(‘id’) > 0 ) {
try {
$Model = Mage::getModel(‘/’);
$Model->setId($this->getRequest()->getParam(‘id’))
->delete();
Mage::getSingleton(‘adminhtml/session’)->addSuccess(Mage::helper(‘adminhtml’)->__(‘Item was successfully deleted’));
$this->_redirect(‘*/*/’);
} catch (Exception $e) {
Mage::getSingleton(‘adminhtml/session’)->addError($e->getMessage());
$this->_redirect(‘*/*/edit’, array(‘id’ => $this->getRequest()->getParam(‘id’)));
}
}
$this->_redirect(‘*/*/’);
}
/**
* Product grid for AJAX request.
* Sort and filter result for example.
*/
public function gridAction()
{
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock(‘/adminhtml__grid’)->toHtml()
);
}
}
XML Configuration Changes
/app/code/local///etc/config.xml
0.1.0
standard
[Namespace]_[Module]
[module]
[module].xml
admin
[Namespace]_[Module]
[module]
71
0
[module]/adminhtml_[module]
200
[module].xml
[Namespace]_[Module]_Model
[module]_mysql4
[Namespace]_[Module]_Model_Mysql4
[module]
[Namespace]_[Module]
core_setup
core_write
core_read
[Namespace]_[Module]_Block
[Namespace]_[Module]_Helper
XML Layout
/app/design/adminhtml///layout/.xml
Seperate Adminhtml Configuration
It’s also worth noting the adminhtml changes in the config.xml (above) can be placed in their own XML file instead, keeping these changes separated away:
/app/code/local///etc/adminhtml.xml
71
0
[module]/adminhtml_[module]
200
[module].xml
Standard Magento Admin URLs, no rewrite needed
Also, rather than using a rewrite for the admin section described above, you can implement the same standard admin generated urls Magento uses. These look like: ‘/admin/[module]/index/’ instead of the above that would generate ‘/[module]/adminhtml_[module]/index/’.
To implement this different url structure you can change the following in your config.xml:
/app/code/local///etc/config.xml


[Namespace]_[Module]_Adminhtml
71
0
adminhtml/[module]

Saturday, June 29, 2013

How to get store URL by store code or store Id

Here are 2 ways to get home URL of Magento stores
1. By store CODE
01
02
03
04
05
06
07
08
09
10
11
12
13
function getStoreByCode($storeCode)
{
        $stores = array_keys(Mage::app()->getStores());
        foreach($stores as $id){
          $store = Mage::app()->getStore($id);
          if($store->getCode()==$storeCode) {
            return $store;
          }
         }
         return null; // if not found
}
$store = getStoreByCode('default');
$store->getUrl('');


2. By store ID
1
2
$storeId = 1;
Mage::getModel('core/store')->load($storeId)->getUrl('');

Friday, June 28, 2013

Magento: Form key in backend

Sometime you try to catch the submit url to handle your request in backend.
E.g. http://localhost/Magento/admin/assign_theme/approve/id/10
You look at the controller and find you have already declare the delete action as
1
2
3
4
5
6
7
class Pamysoft_AssignTheme_IndexController
{
    public function approve()
    {
         echo 'The approving processing should go here!'; exit;
    }
}
Solution:
Add the hidden input form_key to make your form submit correctly
1
2
3
$formKey = Mage::getSingleton('core/session')->getFormKey();
 
<input type="hidden" name="form_key" value="<?php echo $formKey; ?>" />;

Thursday, June 27, 2013

How to load a html content of static block in Magento template

This is snippet for loading HTML content of block named as “company_information”
1
$this->getLayout()->createBlock('cms/block')->setBlockId('company_information')->toHtml()

Sunday, June 23, 2013

SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded try restarting transaction

When developing on some customer site, we have met this error in the report file “SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction“. We have researched about this issue and we have found people suggests to run this statement via phpMyAdmin “SET innodb_lock_wait_timeout = 120;” or restart mysql service. But sometime, we don’t have permission to run this statement and have hosting admin done it.
 We have found other quick solution to do by modifying the file <Magento root folder>/lib/Zend/Db/Statement/Pdo.php at public function _execute(array &params = null)
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public function _execute(array $params = null)
{
   /*try {
      if ($params !== null) {
         return $this->_stmt->execute($params);
      } else {
         return $this->_stmt->execute();
      }
   } catch (PDOException $e) {
      #require_once 'Zend/Db/Statement/Exception.php';
      throw new Zend_Db_Statement_Exception($e->getMessage(), (int) $e->getCode(), $e);
   }*/
    
   $timeoutMessage = 'SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction';
   $tries = 0;
   do {
      $retry = false;
      try {
         if ($params !== null) {
            return $this->_stmt->execute($params);
         } else {
            return $this->_stmt->execute();
         }
      } catch (PDOException $e) {
         if ($tries < 10 and $e->getMessage()==$timeoutMessage) {
            $retry = true;
         } else {
            throw new Zend_Db_Statement_Exception($e->getMessage());
         }
         $tries++;
      }
   } while ($retry);
}

Magento How to change Currency symbol ?

I had a hectic day changing the currency symbol in Magento. Though different blogs and magento forum helped me, I am writing this article for my reference. ;)
I had to change the currency symbol of Nepalese Rupee (from Nrs to Rs). By default, the currency symbol for Nepalese Rupee is Nrs.
For this, you need to edit lib/Zend/Locale/Data/en.xml
Well, the xml file to edit depends upon your locale settings. My locale is set to English (United States). So, I will have to change en.xml file.
You can change your locale setting from
Admin Panel –> System –> Configuration –> GENERAL –> General –> Locale options –> Locale
If your locale is Japanese (Japan), you need to change lib/Zend/Locale/Data/ja.xml
If your locale is Hindi (India), you need to change lib/Zend/Locale/Data/ne.xml
It’s similar for other locale settings. I have locale setting as English, so I will be editing en.xml file.
- Open lib/Zend/Locale/Data/en.xml
- Find the following :-
1
2
3
4
5
6
<currency type="NPR">
    <displayName>Nepalese Rupee</displayName>
    <displayName count="one">Nepalese rupee</displayName>
    <displayName count="other">Nepalese rupees</displayName>
    <symbol>Nrs</symbol>
</currency>
- Change
1
<symbol>Nrs</symbol>
to
1
<symbol>Rs</symbol>
- That’s it.
But wait, you are still not done. The most important thing is still left.
- Clear the Cache.
- Go to System –> Cache Management
- Refreh Cache.
- If you have not enabled the Cache OR if it didn’t work even after refreshing the cache, then
- delete the cache folder present inside var (var/cache)
Now, it should definitely work. :)
I changed the currency symbol for Nepalese Rupee. You can do similarly for your currency type.
Hope this helps. Thanks.
PS: Your changes will be gone when you upgrade Magento. You need to redo the above changes after upgrade.hanges after upgrade.

Creating Varien Object & Collection from any Array data

Varien_Object and Varien_Collection are the parent/super class for most of the Magento Models and Collections respectively.
The path for Varien_Object is lib/Varien/Object & for Varien_Collection is lib/Varien/Data/Collection.php.
This article shows how you can create new Varien objects and collections from any array or object data you have.
Here is the code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
/**
 * Creating new varien collection
 * for given array or object
 *
 * @param array|object $items   Any array or object
 * @return Varien_Data_Collection $collection
 */
public function getVarienDataCollection($items) {
    $collection = new Varien_Data_Collection();
    foreach ($items as $item) {
        $varienObject = new Varien_Object();
        $varienObject->setData($item);
        $collection->addItem($varienObject);
    }
    return $collection;
}

Saturday, June 22, 2013

Magento: how to get custom variables

To get custom variable of Magento you have defined at System > Custom Variables, use the following code to get the values


$plainValue = Mage::getModel('core/variable')->loadByCode('custom_variable_code')->getValue('plain');
$htmlValue = Mage::getModel('core/variable')->loadByCode('custom_variable_code')->getValue('html');