Collection: addFieldToSelect vs select columns
collection->addFieldToSelect('col_name')
will include the ID column in result. To return only columns of interest, use
$collection->getSelect()
->reset(Zend_Db_Select::COLUMNS)
->columns(['col_name']);
Example:
$collection->getSelect()
->reset(Zend_Db_Select::COLUMNS)
->columns(['entity_id' => 'mageproductid', 'value' => 'userid']);
$result = $collection->toArray();
$result
output:
array(2) {
["totalRecords"] => int(1565)
["items"] => array(1565) {
[0] => array(2) {
["entity_id"]...
Zend_Db_Select the last row from each group
Get the last entry of each applicant in history table:
$installer = $this;
$db = $installer->getConnection();
$table = $installer->getTable('table/name');
$select = $db->select()
->from(['t1'=>$table], ['log_id', 'applicant_id', 'grade', 'attendance'])
->joinLeft(['t2'=>$table], 't1.applicant_id = t2.applicant_id AND t1.created_at < t2.created_at', [])
->where('t2.created_at IS NULL');
$items = $db->fetchAll($select);
Default All Product Custom Options to Store 0
If the custom options of a product are the same across stores, but somehow there are not defaulted to store 0, the method below will default all custom options to store 0:
admin > product page > Custom Options > Change to other store > F12 to bring up the dev tools > in console > run
$$('.product-option-scope-checkbox').each(function(e){e.checked=true;})
Or
$$('input[type="checkbox"]').each(function(e) { e.checked = true; });
Then save. Repeat for other store views.
In DB, the entries in the product option tables ...
Check if the current page is homepage
<?php if(!Mage::getBlockSingleton('page/html_header')->getIsHomePage()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php endif ?>
Whitelist Custom Block For Calling in Static Block with Double Curly Brackets
When a block directive, double curly brackets: {{block type="module/block"}} is called in the static block, it is necessary to whitelist the block type in
admin > System > Permissions > Block
. Otherwise, it will not render.
Alternatively, the block can be whitelist in the table permission_block
directly.
Reference Mage_Core_Model_Email_Template_Filter::blockDirective()
Product Custom Option Updates
/**
* Add new radio option 'Moby' to Application Type
* Affect products: i14, i14u, i14g
*/
$optionTitle = 'Application Type';
$values[] = array(
'title' => 'Moby',
'price' => -750,
'sku' => 'co_type_mob1',
'sort_order' => 50,
'option_type_id' => -1,
'is_delete' => 0,
'price_type' => 'fixed'
);
$fields = array(
'max_characters' => 0,
'type' => 'radio',
'title' => $op...
File Upload in Product Custom Option
Each uploaded file is processed here:
Mage_Catalog_Model_Product_Option_Type_File::_validateUploadedFile()
To see the uploaded files:
$result['$_FILES'] = $_FILES;
foreach ($_FILES as $key=>$file) {
$result[$key] = is_uploaded_file($file['tmp_name']);
}
return Mage::helper('clog')->_echo($result);
Exception
exception 'Zend_File_Transfer_Exception' with message 'The file transfer adapter can not find "options_808_file"' in ../lib/Zend/File/Transfer/Adapter/Abstract.php:1503
The exception was due to missing `s...
Add new input type in product custom options
custom module productcoption
config.xml
<config>
<modules>
<Somemod_ProductCoption>
<version>0.0.1</version>
</Somemod_ProductCoption>
</modules>
<global>
<resources>
<productcoption_setup>
<setup>
<module>Somemod_ProductCoption</module>
</setup>
</productcoption_setup>
</resources>
<blocks>
<productcoption>
<...
updateFromSelect
How to update a column in main table from another table's column. Reference:
Varien_Db_Adapter_Pdo_Mysql::updateFromSeelct()
/**
* UPDATE maintable t1
* JOIN sales_flat_order t2 ON t1.application_id = t2.increment_id
* SET t1.stud_id = t2.appl_id
* WHERE t1.student_id IS NULL
*/
public function updateStudId()
{
$adapter = $this->_getWriteAdapter();
$select = $adapter->select()
->from($this->getMainTable(), array())
->joinLeft(a...
addFieldToFilter
OR
$collection->addFieldToFilter('field_name',
[
['eq' => 'value1'],
['eq' => 'value2']
]
);
// same as
$collection->addFieldToFilter('field_name', ['value1', 'value2']);
Filter for X or Y
$collection->addFieldToFilter(
['k1' => 'mc_status', 'k2' => 'mc_fail'],
['k1' => ['in' => [21, 22]], 'k2' => ['null'=> true]]
);
The above retrieves:
SELECT `main_table`.*
FROM `some_table` AS `main_table`
WHERE ((mc_status IN(21, 22)) OR (mc_fail IS NULL))
NULL, NOT NULL
...
Form Field
A sample of different options to add field in Mage_Adminhtml_Block_Widget_Form
Ref Varien_Data_Form_Element_Abstract
lib\Varien\Data\Form\Element\Abstract.php
Add Suffix to Element Names
$form = new Varien_Data_Form(['field_name_suffix' => 'ihe']);
Date and Date-time Fields
$dateFormatIso = Mage::app()->getLocale()->getDateFormat(
Mage_Core_Model_Locale::FORMAT_TYPE_SHORT
);
$fieldset->addField('established_at', 'date', [
'name' => 'established_at',
'image' => $this->getSkinUrl('i...
Controller Action Response
json response
public function completeAction()
{
$orderId = $this->getRequest()->getParam('order_id', false);
$info['order_id'] = 0;
if ($orderId) {
$order = Mage::getModel('patron/order')->load($orderId);
if ($info['order_id'] = $order->getId()) {
$info['ostatus'] = $order->getOstatus();
$info['lat'] = $order->getDeliveredLat();
$info['lng'] = $order->getDeliveredLng();
}
}
$this->getResponse()->setHeader(...
Grid Column Options
Column Types
Take a look at Mage_Adminhtml_Block_Widget_Grid_Column::_getRendererByType()
to dive into the different column types:
app\code\core\Mage\Adminhtml\Block\Widget\Grid\Column\Renderer\Abstract.php
- date
- datetime
- number
- currency
- price
- country
- concat
- action
- options
- checkbox
- massaction
- radio
- input
- select
- text
- store
- wrapline
- theme
Code Snippets
Checkbox
See app\code\core\Mage\Adminhtml\Block\Widget\Grid\Column\Renderer\Checkbox.php
.
protected function _p...
Order Currency & Rate
base_currency_code
Base currency is used for all online payment transactions. Scope is defined by the catalog price scope ("Catalog" > "Price" > "Catalog Price Scope").
global_currency_code
The default currency configured in the admin, Default Display Currency
order_currency_code
The currency with which order is placed.
store_currency_code
Deprecated, same as base.
base_to_global_rate
Convert from base to global
base_to_order_rate
Convert from base to order, ratio of grand_total and base_grand_total
Magento Stores
Load Store by Store Code
$store = Mage::getModel('core/store')->load('store_code');
// or
$store = Mage::app()->getStore('store_code');
Get Store URL
$store->getBaseUrl();
Get Store Secure URL
$store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK, true);
Cancel credit memo
UPDATE `sales_flat_order` SET
`base_discount_refunded`=null,
`base_shipping_refunded`=null,
`base_shipping_tax_refunded`=null,
`base_subtotal_refunded`=null,
`base_tax_refunded`=null,
`base_total_offline_refunded`=null,
`base_total_online_refunded`=null,
`base_total_refunded`=null,
`discount_refunded`=null,
`shipping_refunded`=null,
`shipping_tax_refunded`=null,
`subtotal_refunded`=null,
`tax_refunded`=null,
`total_offline_refunded`=null,
`total_online_refunded`=null,
`total_refunded`=null,
`hidden_tax_refunded`=null,
`base_hidden_tax_re...
Magento image load error: fileUploadErrorCantWrite
The error is coming from Mage_Catalog_Model_Product_Option_Type_File
but it is not interpreted in _getValidatorErrors()
. The error happens repeatedly for certain users and not other users.
In $fileInfo = $upload->getFileInfo($file);
, the error is 7. For example:
Array
(
[name] => YU XIA.jpg
[type] =>
[tmp_name] =>
[error] => 7
[size] =>
[options] => Array
(
[ignoreNoFile] =>
[useByteString] => 1
[magicFile] =>
[detectInfos] => 1
)
[...
Magento Resize Image
/**
* Resize image recursively until it is less than 25KB and saved as tmp.jpg
* Original image is unchanged
*
* @param string fullpath and filename
* @return string fullpath tmp.jpg that is saved
*/
protected function _resizeImage($fnm)
{
if (filesize($fnm) > 25600) {
$image = new Varien_Image($fnm);
$image->constrainOnly(false);
$image->keepAspectRatio(true);
$newW = (int) $image->getOriginalWidth() * ...
Filter EAV collection
condA AND (cond1 OR cond2 OR cond3)
$cincId = $session->getCustomerId();
$attributes = array(
array('attribute'=>'mc_by', 'eq'=>$clinicId),
array('attribute'=>'mc_lb_by', 'eq'=>$clinicId),
array('attribute'=>'mc_xy_by','eq'=>$clinicId),
);
$students = Mage::getResourceModel('moe/stut_collection')
->addAttributeToSelect(array('fullname', 'travel_doc_no', 'mc_status'))
->addAttributeToFilter($attributes, null, 'left')
->setOrder('created_at', 'desc')
;
Short Array:
...