Datetime in DB

There are 2 column types:

// lib\Varien\Db\Ddl\Table.php
    const TYPE_TIMESTAMP        = 'timestamp'; // Capable to support date-time from 1970 + auto-triggers in some RDBMS
    const TYPE_DATETIME         = 'datetime'; // Capable to support long date-time before 1970

All columns are of type Varien_Db_Ddl_Table::TYPE_TIMESTAMP in OpenMage, except for customer_dob and columns in eav datetime tables, which are of type Varien_Db_Ddl_Table::TYPE_DATETIME.

MySQL converts TIMESTAMP values from the current time zone to UTC f...

Column Collation in Table

This doesn't work:

    ->addColumn('name', Varien_Db_Ddl_Table::TYPE_TEXT, 200, array(
        'nullable'  => false,
        'collate'   => 'utf8mb4_unicode_ci' // doesn't work
        ), 'Name')

That's because it is ignored:

// lib\Varien\Db\Ddl\Table.php
public function addColumn($name, $type, $size = null, $options = array(), $comment = null)
{
//...
    $this->_columns[$upperName] = array(
        'COLUMN_NAME'       => $name,
        'COLUMN_TYPE'       => $type,
        'COLUMN_POSITION'   => $position,
        'DA...

validation.js

/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
*
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software,...

REST API

Official Guide

M1 doc.

OM GitHub Issue

Test Script in devdocs-openmage.org

stackoverflow

[magento.stackexchange.com/how-to-create-rest-api-for-the-magento-1-9-hosted-in-local-machine](https://magento.stackexchange.com/questions/115827/how-to-c...

Fix Race Condition

Fix At Adapter Level

// app\code\core\Mage\CatalogInventory\Model\Resource\Stock.php    
/**
 * Correct particular stock products qty based on operator
 *
 * @param Mage_CatalogInventory_Model_Stock $stock
 * @param array $productQtys
 * @param string $operator +/-
 * @return $this
 */
public function correctItemsQty($stock, $productQtys, $operator = '-')
{
    if (empty($productQtys)) {
        return $this;
    }

    $adapter = $this->_getWriteAdapter();
    $conditions = array();
    foreach ($productQtys as $productId => $qty)...

Adminhtml JSON Response Body

HTML

public function visibleProductsAction()
{
    $this->getResponse()->setBody(
        $this->getLayout()->createBlock('module/adminhtml_block_type')->toHtml()
    );
}

Generic Block:

$block = $this->getLayout()->createBlock('adminhtml/template')
    ->setTemplate('system/autocomplete.phtml')
    ->assign('items', $items);

$this->getResponse()->setBody($block->toHtml());

Array

class Mage_Adminhtml_JsonController extends Mage_Adminhtml_Controller_Action
{
    /**
     * Return JSON-encoded array of count...

Dataflow Import/Export Profiles

Import Sample Actions XML:

<action type="dataflow/convert_adapter_io" method="load">
   <var name="type">file</var>
   <var name="path">var/import</var>
   <var name="filename"><![CDATA[filename.csv]]></var>
   <var name="format"><![CDATA[csv]]></var>
 </action>
<action type="dataflow/convert_parser_csv" method="parse">
    <var name="delimiter"><![CDATA[,]]></var>
    <var name="enclose"><![CDATA["]]></var>
    <var name="fieldnames"></var>
    <var name="map">
        <map name="Col Name in File"><![CDATA[fieldname_in_system]]></...

Modify Column in Table

Change Text Length

/** @var Mage_Core_Model_Resource_Setup $installer */
$installer = $this;
$installer->startSetup();
/** @var Varien_Db_Adapter_Pdo_Mysql $connection */
$connection = $installer->getConnection();

$table = $installer->getTable('sales/order_item');
// Using modifyColumn()
$installer->getConnection()->modifyColumn($table, 'product_options', 'MEDIUMTEXT');
// Using changeColumn()
$installer->getConnection()->changeColumn(
    $table,
    'product_options',
    'product_options',
    [
        'type' =>  Varien_Db_Ddl_...

JOINS in Zend_Db_Select

OM uses Zend Version 1.12.16.

Adding Another Table to the Query with JOIN

Many useful queries involve using a JOIN to combine rows from multiple tables. You can add tables to a Zend_Db_Select query using the join() method. Using this method is similar to the from() method, except you can also specify a join condition in most cases.

// Build this query:
//   SELECT p."product_id", p."product_name", l.*
//   FROM "products" AS p JOIN "line_items"...

Translation

DO NOT use inline translation. The inline translations are stored in the table core_translate. Backup the table, convert all entries to a file translate.csv. Then configure the following.

Set up translation in the theme

Backend > System > Configuration > set the Current Configuration Scope to the store of interest, then go to Design > Theme > Translation and set the name of the theme:

Image

Then create or save the file translate.csv in app\design\frontend\<PACKAGE>\visa\locale\en_GB.

FIle Download

Generate the URL:

    /**
     * For file and image field, get the file URL
     * 
     * @see Mage_Customer_Model_Attribute_Data_File
     * @return string
     */
    public function getFileUrl()
    {
        return $this->getUrl('extendedcustomer/account/viewfile', array(
            'file'      => Mage::helper('core')->urlEncode($this->getValue()),
        ));
    }

Controller:

class Scicom_ExtendedCustomer_AccountController extends Mage_Core_Controller_Front_Action
{
    /**
     * @see Mage_Adminhtml_CustomerCont...

nginx config

See production grade nginx and docker config here.

Some notes on this:

  • the PCI work was trial and error, we did set up, the external audit did penetration/probe testing, we adjusted settings until given a pass
  • we used to use hhvm until php 7 turned up. Boy was that a speed advantage back in the php 5 days
  • Note that we dont service any traffic unless it comes from CDN, protecting magneto php code from noise can really reduce load on you systems
  • we use plenty of rate limiting as th...

_prepareLayout

Add css

protected function _prepareLayout()
{
    $this->getLayout()->getBlock('head')->addCss('course/form.css');
    $this->setTitle('Course Eligibility Result');
    return parent::_prepareLayout();
}

Set Child Block

protected function _prepareLayout()
{       
    parent::_prepareLayout();
    $this->setChild('setForm', $this->getLayout()->createBlock('extendedcustomer/adminhtml_attribute_set_main_formset'));
    return $this;
}

Add Button

protected function _prepareLayout()
{
    $this->_addButton('s...

When there is no payment methods on onepage checkout page

There are many reasons why a payment method is not listed or missing on the checkout page:

  1. admin > System > Configuration > Sales > Payment Methods >
    1. check that the payment methods are enabled
    2. check for min and max amount of the payment method
    3. check for applicable countries or any other configurable values which can prevent the method from being listed
  2. [3rd-party extension] admin > Customers > Customer Group > select a group > Group Payment Methods > check that the payment methods are selected for the customer gr...

How to use cache in OpenMage / Magento 1.x to speed things up

Mechanism: cache in model

First, save the cache

// app\code\core\Mage\Core\Model\App.php Mage_Core_Model_App
/**
 * Saving cache data
 *
 * @param   mixed $data
 * @param   string $id
 * @param   array $tags
 * @param null|false|int $lifeTime
 * @return  $this
 */
public function saveCache($data, $id, $tags = [], $lifeTime = false)
{
    $this->_cache->save($data, $id, $tags, $lifeTime);
    return $this;
}

$id is a unique string that identify the cache. It is customary all uppercase.

If $tags doesn't have `Mage_Core_M...

Load Additional Config in config.mysql4.xml

We can use this file name config.mysql4.xml to load additional configuration in the module's etc folder, the folder which contains config.xml.

Varien_Data_Form Fieldset Options

Wide field

Useful for long text.

$form = new Varien_Data_Form();

$fieldset = $form->addFieldset('base_fieldset', [
    'legend' => Mage::helper('im')->__('Comment'),
   // 'comment' => 'non-html text is rendered before other fields',
    'class' => 'fieldset-wide'
]);

        $fieldset->addField('comment', 'textarea', [
            'name'      => 'comment',  
            'required'  => true,
            'after_element_html' => "<script>$('comment').up('td').previous('td').remove();$('comment').up('td').colspan=2;</script>"
     ...

Warning: Invalid argument supplied for foreach() in lib/Zend/Locale/Format.php on line 853

PHP Version 7.4.7 OpenMage 1.9.4.5

if ($day !== false) {
    $parse[$day]   = 'd';
    if (!empty($options['locale']) && ($options['locale'] !== 'root') &&
        (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {
        // erase day string
            $daylist = Zend_Locale_Data::getList($options['locale'], 'day');
        foreach($daylist as $key => $name) {
            if (iconv_strpos($number, $name) !== false) {
                $number = str_replace($name, "EEEE", $number);
                break;
 ...

Cannot Login in Frontend

Make sure the backend > System > Configuration > Web > Session Cookie Management > Cookie Domain is configured correctly for each store.

Image

How to Set Date Format by Locale in Magento 1

Each locale has different date formats. The default settings are configured in xml files located in lib\Zend\Locale\Data. The locale is configured in backend

System > Configuration > General > Locale Options > Locale

For example, if we set the Locale to English (United Kingdom), which value is en_GB. To look up the default date formats, look at the file lib\Zend\Locale\Data\en_GB.xml:

<dateFormats>
    <dateFormatLength type="full">
        <dateFormat>
            <pattern>EEEE, d MMMM U</pattern>
        </dateFormat>
 ...

How to add TCPDF to Library to Magento 1

We can add a 3rd-party to library to Magento, for example TCPDF.

  1. Download the library and unzip.
  2. Place the unzip contents to /lib/Tcpdf/.
  3. For autoloading by Magento, we need to change the main application class name to Mage standard (separated by underscore): <folder-name>_<original-class-name>; for TCPDF, we edit the file Tcpdf.php: the original class name is class TCPDF, we change it to class Tcpdf_Tcpdf.
    1. class Tcpdf_Tcpdf
    2. class Tcpdf_Tcpdf2DBarcode
  4. No we can ins...

Link Top Menu Item to Product View

Top menu is configured in backend > Catalog > Manage Categories. The landing page can be set to product list, static block, or a combination of both. But what if we want to by pass the product listing and land on a product page? Here's the technique I use to do just that:

[vs code] Create a Couple of Blocks

/**
 * es Module
 *
 * @category   Celera
 * @package    Celera_Es
 * @copyright  Copyright (c) 2019 Ng Kiat Siong, Celera eShop, kiatsiong.ng@gmail.com  
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software...

Set custom URL to 'Add to Cart' in Backend Product Page

admin > product page > Design > Custom Layout Update:

<reference name="content">
    <block type="es/catalog_product_view_layoutUpdate_application" name="layoutupdate_application"/>
</reference>
<reference name="product.info">
    <action method="setCustomAddToCartUrl"><url>/controller/catalog_product/route</url></action>
</reference>
<reference name="head">
    <action method="addItem"><type>skin_js</type><name>js/aes.js</name>
    <action method="addJs"><script>dir/jsonp.js</script></action>
</action>
</reference>

Insert Vue.j...