1

URL

//Get Base Url
Mage::getBaseUrl();

//Get Skin Url
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);

//Unsecure Skin Url
$this->getSkinUrl('images/imagename.jpg');

//Secure Skin Url
$this->getSkinUrl('images/imagename.gif', array('_secure'=>true));

//Get Media Url
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);

//Get Js Url
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);

//Get Store Url
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);

//Get Current Url
Mage::helper('core/url')->getCurrentUrl();

Url Tag

{{store url=""}} : 获取站点根URL,一般是域名
{{store url="path/"}} :    获取站点根URL + “path/”的路径,其中path/可被任何有效地址代替
{{skin url=""}} : 获取当前Store view 的皮肤URL
{{skin url="path/fileName"}} : 获取当前Store view 的皮肤URL + 路径 + 文件名
{{media url=""}} : 获取media 的根URL
{{media url="path/fileName"}} : 获取media 的根URL + 路径 + 文件名

Add JS and CSS from Layout

<reference name="head">
    <action method="addItem">
        <type>skin_css</type>
        <name>css/yourstyle.css</name>
    </action>
    <action method="addItem">
        <type>skin_js</type>
        <name>js/yourscript.js</name>
        <params/>
    </action>
</reference>

include another controller

require_once Mage::getModuleDir( 'controllers', 'Mage_Wishlist' ) . DS . 'IndexController.php';

Calling Static Blocks directly from .phtml files

echo $this->getLayout()->createBlock("cms/block")->setBlockId("block_identifier")->toHtml();

echo $this->getChildHtml('blockname'); // 需要在layout上定义block

Calling Block/Template from admin CMS pages and static blocks

{{ block type="module/block" template="module/template.phtml" category_id="25" }}

Breadcurmbs anywhere

echo $this->getLayout()->getBlock("breadcrumbs")->toHtml();

XML layout引用block

<reference name="content">
    <block type="cms/block" name="blockname" before="-">
        <action method=”setBlockId”><id>block_id</id></action>
    </block>
</reference>

phtml里引用其它模板

echo $this->getLayout()->createBlock(
    'core/template', 'block_name', array(
    'template' => 'xxxx/xxxx.phtml',
    )
)->toHtml();

Image re-size in Magento

echo $this->helper('catalog/image')->init($_product, 'image')
    ->constrainOnly(TRUE)
    ->keepAspectRatio(TRUE)
    ->keepFrame(FALSE)
    ->resize(150,null)

Keep height fixed (In the code below, fixed to 200px)

echo $this->helper('catalog/image')->init($_product, 'image')
    ->constrainOnly(TRUE)
    ->keepAspectRatio(TRUE)
    ->keepFrame(FALSE)
    ->resize(null,200)

Re-size image proportionally and keep the image width and height not greater than the specified width and height

echo $this->helper('catalog/image')->init($_product, 'image')
    ->constrainOnly(TRUE)
    ->keepAspectRatio(TRUE)
    ->keepFrame(FALSE)
    ->resize(200,200)

In the example above, either width or height, whichever is bigger will be re-sized to 200px and the other will be re-sized proportionally.
Re-size image proportionally to the specified width and height
In the example above, if the original image’s height was bigger than the width, height will be 200px and width will be smaller. However, if we want the new re-sized image to be 200px by 200px, the following code will make the height 200px and width will also be 200px by filling in the blank space with white.

echo $this->helper('catalog/image')->init($_product, 'image')
    ->constrainOnly(TRUE)
    ->keepAspectRatio(TRUE)
    ->keepFrame(TRUE)
    ->resize(200,200)

is login

Mage::getSingleton('customer/session')->isLoggedIn();

Working with product attributes

// Get attribute collection
$attribute = $_product->getResource()->getAttribute('my_attribute');

// Get attribute label
$attribute->getFrontendLabel();

// Get attribute default value
$attribute->getDefaultValue();

// Get attribute value
$attributeValue = Mage:getModel('catalog/product')
    ->load($_product->getId())->getMyAttribute();

model

$collections = Mage::getModel('hm_faq/faq')->getCollection()
    ->addFieldToSelect(array('*'))
    ->addFieldToFilter('sku', array('like' => 'UX%'))
    ->setOrder('ordering', 'ASC');

product images

/* @var $mediaApi Mage_Catalog_Model_Product_Attribute_Media_Api*/
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
foreach($items as $item) {
    $mediaApi->info($product->getId(), $item['file']);
    $mediaApi->update($product->getId(), $item['file'], ['exclude' => 1, 'types' => ['small_image']]);
    $mediaApi->remove($product->getId(), $item['file']);
}

product

// product collection filter
$_products = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect(array('name', 'product_url', 'small_image'))
    ->addAttributeToFilter('sku', array('like' => 'UX%')) // sku like 'UX%'
    ->addAttributeToFilter(array(
        array('attribute' => 'price', 'eq'=> 0.00),
        array('attribute' => 'name', 'like'=> 'prefix%')
    )) // price=0.00 OR name LIKE 'prefix%'
    ->load();

//Get Product Name
$product->getName();

//Get product sku
$product->getSku();

//Get product stock
Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();

//Get a product attribute value (like color/size)
$product->getResource()->getAttribute('color')->getFrontend()->getValue($product);

//checks if a product is salable
$product->isSaleable();

//checks if a product type is salable
$product->isisAvailable();

//Gets the product final price after all catalog rules have been applied
Mage::getModel('catalogrule/rule')->calcProductPriceRule($product,$product->getPrice());

//Gets the product tier price if can be applied to the customer
$product->getTierPrice(1);

//How do I get the display value of a (multi-)select product attribute?
echo $product->getAttributeText('manufacturer');

//How do I get the configurable/grouped/bundled
//product a simple product belongs to?
$simpleProduct->loadParentProductIds();
$parentProductIds = $simpleProduct->getParentProductIds();

//How do I get the simple products assigned to a configurable product?
$configProduct->getTypeInstance()->getUsedProductCollection($configProduct);

product addAttributeToFilter

//Equals: eq
$_products->addAttributeToFilter('status',array('eq'=> 1));

//Not Equals - neq
$_products->addAttributeToFilter('sku',array('neq'=>'test-product'));

//Like - like
$_products->addAttributeToFilter('sku',array('like'=>'UX%'));

//Not Like - nlike
$_products->addAttributeToFilter('sku',array('nlike'=>'err-prod%'));

//In - in
$_products->addAttributeToFilter('id',array('in'=>array(1,4,74,98)));

//Not In - nin
$_products->addAttributeToFilter('id',array('nin'=>array(1,4,74,98)));

//NULL - null
$_products->addAttributeToFilter('description','null');

//Not NULL - notnull
$_products->addAttributeToFilter('description','notnull');

//Greater Than - gt
$_products->addAttributeToFilter('id',array('gt'=> 5));

//Less Than - lt
$_products->addAttributeToFilter('id',array('lt'=> 5));

//Greater Than or Equals To- gteq
$_products->addAttributeToFilter('id',array('gteq'=> 5));

//Less Than or Equals To - lteq
$_products->addAttributeToFilter('id',array('lteq'=> 5));

EAV

$typeId = Mage::getModel('eav/entity')
    ->setType('customer_address')
    ->getTypeId();
$collections = Mage::getResourceModel('eav/entity_attribute_collection')
    ->setEntityTypeFilter($typeId)
    ->addFieldToFilter("is_user_defined", 1)
    ->setOrder('sort_order', $direction = Varien_Data_Collection::SORT_ORDER_DESC);

Get information

//Get host name
echo Mage::app()->getFrontController()->getRequest()->getHttpHost();

//Get base direcrory
echo Mage::getBaseDir();

//Get base URL
echo Mage::getBaseURL();
//or 
echo Mage::getURL();

//Get default skin folder
$this->getSkinURL('images/myfile.png'); // in a template or Block
Mage::getDesign()->getSkinUrl('images/myfile.png'); // from anywhere

//Get the referer URL
$this->getRequest()->getServer('HTTP_REFERER'); 

//How do I format a price value?
Mage::helper('core')->formatPrice($amount);

//How do I create an object instance in magento?
Mage::getModel('module/class'); // for models
Mage::helper('module/class'); // for helpers
Mage::app()->getLayout()->createBlock('module/class', 'name_in_layout'); // for blocks

//How do I get at GET/POST parameters?
Mage::app()->getRequest()->getParam('param_name'); // single parameter
Mage::app()->getRequest()->getParams(); // all parameters

//How do I get the Id of the curent store view?
Mage::app()->getStore()->getId();

//How do I get all Store Views?
Mage::app()->getStores(); // pass true to include the admin store view, too

//How do I get an instance of an attribute?
Mage::getSingleton('eav/config')->getAttribute($entityType, $attributeCode)

// cart info
Mage::getSingleton('checkout/cart')->getQuote()->getShippingAddress();

// region
$regionModel = Mage::getModel('directory/region')->load($region_id);
$regionModel = Mage::getModel('directory/region')->loadByCode($regionCode, $countryCode);
$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($this->getCountryId())
->load();

SQL

$read= Mage::getSingleton('core/resource')->getConnection('core_read');  
$query = $read->query("SELECT MAX(sortorder) AS maxorder FROM storelocator");
$row = $query->fetch();
$maxorder = $row['maxorder'];

// print SQL
$collection->load()->getSelectSql(true);

setup script

$installer = $this;

$table = $installer->getTable( 'digitalstore/epc' );

$installer->getConnection()->addColumn(
    $table, 'updated_at', 'datetime default null'
);

$installer->getConnection()->addColumn(
    $table, 'expiry', 'datetime default null'
);

$installer->getConnection()->addIndex(
    $table, $installer->getIdxName( 'digitalstore/epc', array( 'updated_at' ) ), array( 'updated_at' ),
    Varien_Db_Adapter_Interface::INDEX_TYPE_INDEX 
);

$installer->getConnection()->addIndex(
    $table, $installer->getIdxName( 'digitalstore/epc', array( 'expiry' ) ), array( 'expiry' ),
    Varien_Db_Adapter_Interface::INDEX_TYPE_INDEX
);

cache

$cacheTags = array('config');
if ($dataCache = Mage::app()->loadCache($cacheId)) {
    $data = unserialize($dataCache);
}
Mage::app()->saveCache(serialize($data), $cacheId, $cacheTags);

config

Mage::getStoreConfig('sales_email/order_comment/enabled');

$updateconfigdata = new Mage_Core_Model_Config();
$updateconfigdata->saveConfig('general/store_information/name', "My New Store Name", 'default', 0);

猫之良品
2.5k 声望139 粉丝

资深Drupal, magento与Joomla


引用和评论

1 篇内容引用
0 条评论