1,获得store的配置变量

Mage::getStoreConfig('sectionname/groupname/fields');
1
Mage::getStoreConfig('sectionname/groupname/fields');

2,设置store的配置变量

Mage::getModel('core/config')->saveConfig('YOUR_PATH_HERE', $value );
1
Mage::getModel('core/config')->saveConfig('YOUR_PATH_HERE', $value );

3,获取Ip地址

[code]
// 返回Ip地址的字符串格式:127.0.0.1
echo Mage::helper('core/http')->getRemoteAddr();
// 返回Ip地址的数值格式:2130706433
echo Mage::helper('core/http')->getRemoteAddr(true);
[/code]

4,Get all websites and stores in Magento

[code]
foreach (Mage::app()->getWebsites() as $website) {
foreach ($website->getGroups() as $group) {
$stores = $group->getStores();
foreach ($stores as $store) {
//$store is a store object
}
}
}
[/code]

5,快捷格式化商品价格

echo Mage::helper('core')--->currency($product->getPrice());
1
echo Mage::helper('core')--->currency($product->getPrice());

6,格式化时间

原始日期: <?php echo $timeLapseBegin ?>
Full Date: <?php echo Mage::helper('core')->formatDate($timeLapseBegin, 'full',true); ?>
Long Date: <?php echo Mage::helper('core')->formatDate($timeLapseBegin, 'long',false); ?>
Medium Date: <?php echo Mage::helper('core')->formatDate($timeLapseBegin, 'medium',true); ?>
Short Date: <?php echo Mage::helper('core')->formatDate($timeLapseBegin, 'short',true); ?>
最后一个参数是’false’或’true’,是否显示时分秒。
1
2
3
4
5
6
原始日期: <?php echo $timeLapseBegin ?>
    Full Date: <?php echo Mage::helper('core')->formatDate($timeLapseBegin, 'full',true); ?>
    Long Date: <?php echo Mage::helper('core')->formatDate($timeLapseBegin, 'long',false); ?>
    Medium Date: <?php echo Mage::helper('core')->formatDate($timeLapseBegin, 'medium',true); ?>
    Short Date: <?php echo Mage::helper('core')->formatDate($timeLapseBegin, 'short',true); ?>
最后一个参数是’false’或’true’,是否显示时分秒。

7,快捷获取LOGO

路径<?php echo Mage::getDesign()->getSkinUrl( Mage::getStoreConfig('design/header/logo_src')) ?>
ALT<?php echo Mage::getStoreConfig('design/header/logo_alt') ?>
1
2
路径<?php echo Mage::getDesign()->getSkinUrl( Mage::getStoreConfig('design/header/logo_src')) ?>
ALT<?php echo Mage::getStoreConfig('design/header/logo_alt') ?>

8,用户中心菜单增删改

删除:
unset($_links['tags']);
修改:
$_links['address_book']['label']='我的地址簿';

$_links的所有’name’

account(账户显示板)
account_edit(账户信息)
address_book(地址薄)
orders(我的订单)
billing_agreements(记账协议)
recurring_profiles(循环设定档)
reviews(我的产品评价)
tags(我的标签)
wishlist(我的收藏)
OAuth Customer Tokens(我的应用程序)
newsletter(新闻邮件订阅)
downloadable_products(我的可下载产品)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
删除:
unset($_links['tags']);
修改:
$_links['address_book']['label']='我的地址簿';
 
$_links的所有’name’
 
account(账户显示板)
account_edit(账户信息)
address_book(地址薄)
orders(我的订单)
billing_agreements(记账协议)
recurring_profiles(循环设定档)
reviews(我的产品评价)
tags(我的标签)
wishlist(我的收藏)
OAuth Customer Tokens(我的应用程序)
newsletter(新闻邮件订阅)
downloadable_products(我的可下载产品)

9,添加删除一个系统Attribute

增加:<?php $setup = new Mage_Eav_Model_Entity_Setup('core_setup'); $setup->addAttribute('customer', 'customcode', array( 'label' => 'customcode', 'type' => 'varchar', 'visible' => true, 'required' => false, 'sort_order' = > 10 )); ?>
删除:<?php $setup = new Mage_Eav_Model_Entity_Setup('core_setup'); $setup->removeAttribute('customer', 'customcode'); ?>
修改:$installer->updateAttribute('catalog_product','short_description','is_required',0);
1
2
3
增加:<?php $setup = new Mage_Eav_Model_Entity_Setup('core_setup'); $setup->addAttribute('customer', 'customcode', array( 'label'        => 'customcode', 'type'        => 'varchar', 'visible'    => true, 'required'    => false, 'sort_order' = > 10 )); ?>
删除:<?php $setup = new Mage_Eav_Model_Entity_Setup('core_setup'); $setup->removeAttribute('customer', 'customcode'); ?>
修改:$installer->updateAttribute('catalog_product','short_description','is_required',0);

10,Magento获取客户端IP:

// 返回Ip地址的字符串格式:127.0.0.1
echo Mage::helper('core/http')->getRemoteAddr();

// 返回Ip地址的数值格式:2130706433
echo Mage::helper('core/http')->getRemoteAddr(true);

1
2
3
4
5
// 返回Ip地址的字符串格式:127.0.0.1
echo Mage::helper('core/http')->getRemoteAddr();
 
// 返回Ip地址的数值格式:2130706433
    echo Mage::helper('core/http')->getRemoteAddr(true);

11,Magento: Get checkout cart total details | Subtotal/Grandtotal/Discount/Tax:

$totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount(); //total items in cart
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object
$subtotal = round($totals["subtotal"]->getValue()); //Subtotal value
$grandtotal = round($totals["grand_total"]->getValue()); //Grandtotal value
if(isset($totals['discount']) && $totals['discount']->getValue()) {
$discount = round($totals['discount']->getValue()); //Discount value if applied
} else {
$discount = '';
}
if(isset($totals['tax']) && $totals['tax']->getValue()) {
$tax = round($totals['tax']->getValue()); //Tax value if present
} else {
$tax = '';
}
获取订单地址信息:$order->getShippingAddress()->getData()
获取订单支付信息:$order->getPayment()->getData()
$order->getPayment()->getMethodInstance()->getCode()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount(); //total items in cart
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object
$subtotal = round($totals["subtotal"]->getValue()); //Subtotal value
$grandtotal = round($totals["grand_total"]->getValue()); //Grandtotal value
if(isset($totals['discount']) &#038;& $totals['discount']->getValue()) {
    $discount = round($totals['discount']->getValue()); //Discount value if applied
} else {
    $discount = '';
}
if(isset($totals['tax']) &#038;& $totals['tax']->getValue()) {
    $tax = round($totals['tax']->getValue()); //Tax value if present
} else {
    $tax = '';
}
获取订单地址信息:$order->getShippingAddress()->getData()
获取订单支付信息:$order->getPayment()->getData()
$order->getPayment()->getMethodInstance()->getCode()

12,Magento – 获取订单支付信息:

$order_id = 2314; //use your own order id
$order = Mage::getModel("sales/order")->load($order_id); //load order by order id
$payment_method_code = $order->getPayment()->getMethodInstance()->getCode();
1
2
3
$order_id = 2314; //use your own order id
$order = Mage::getModel("sales/order")->load($order_id); //load order by order id
$payment_method_code = $order->getPayment()->getMethodInstance()->getCode();

13,获取网站基本信息:

Echo Store ID:<?php echo Mage::app()->getStore()->getId(); ?>
Echo Store View Name: <?php echo Mage::app()->getStore()->getName(); ?>
Echo Store Group Name: <?php echo Mage::app()->getStore()->getGroup()->getName(); ?>
Echo Website Name: <?php echo Mage::app()->getWebsite()->getName(); ?>
1
2
3
4
Echo Store ID:<?php echo Mage::app()->getStore()->getId(); ?>
Echo Store View Name: <?php echo  Mage::app()->getStore()->getName(); ?>
Echo Store Group Name: <?php echo  Mage::app()->getStore()->getGroup()->getName(); ?>
Echo Website Name: <?php echo  Mage::app()->getWebsite()->getName(); ?>

14,获取订单状态:

$order->getStatusLabel()//状态名称
$order->getStatus()//状态代码
获取所有历史状态:

<?php foreach ($this->getOrder()->getStatusHistoryCollection(true) as $_item): ?>
$this->helper('core')->formatDate($_item->getCreatedAtDate(), 'medium')//操作时间
$_item->getStatusLabel()//状态名称
<?php if ($this->isCustomerNotificationNotApplicable($_item)): ?>//是否通知用户
<?php echo $this->helper('sales')->__('Notification Not Applicable') ?>
<?php elseif ($_item->getIsCustomerNotified()): ?>
<?php echo $this->helper('sales')->__('Notified') ?>
<img src="<?php echo $this->getSkinUrl('images/ico_success.gif') ?>" width="16" height="16" alt="" />
<?php else: ?>
<?php echo $this->helper('sales')->__('Not Notified') ?>
<?php endif; ?>
//备注描述
<?php if ($_item->getComment()): ?>
<br/><?php echo $this->escapeHtml($_item->getComment(), array('b','br','strong','i','u')) ?>
<?php endif; ?>
<?php endforeach; ?>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$order->getStatusLabel()//状态名称
$order->getStatus()//状态代码
获取所有历史状态:
 
<?php foreach ($this->getOrder()->getStatusHistoryCollection(true) as $_item): ?>
$this->helper('core')->formatDate($_item->getCreatedAtDate(), 'medium')//操作时间
$_item->getStatusLabel()//状态名称
<?php if ($this->isCustomerNotificationNotApplicable($_item)): ?>//是否通知用户
                <?php echo $this->helper('sales')->__('Notification Not Applicable') ?>
                <?php elseif ($_item->getIsCustomerNotified()): ?>
                <?php echo $this->helper('sales')->__('Notified') ?>
                <img src="<?php echo $this->getSkinUrl('images/ico_success.gif') ?>" width="16" height="16" alt="" />
                <?php else: ?>
                <?php echo $this->helper('sales')->__('Not Notified') ?>
                <?php endif; ?>
//备注描述
<?php if ($_item->getComment()): ?>
                <br/><?php echo $this->escapeHtml($_item->getComment(), array('b','br','strong','i','u')) ?>
            <?php endif; ?>
<?php endforeach; ?>

15,top.link的添加删除:

添加:
<action method="addLink" translate="label title">
<label>帮助中心</label>
<url>help</url>
<title>帮助中心</title>
<prepare>true</prepare>
<urlParams helper="core/url/getHomeUrl"/>
<position>555</position>
<liParams/>
<!--<aParams>class="top-link-about-us"</aParams>-->
<beforeText></beforeText>
<afterText></afterText>
</action>

删除:
1、<remove name="checkout_cart_link" />
2、<action method="removeLinkByUrl"><url helper="customer/getAccountUrl"/></action>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
添加:
<action method="addLink" translate="label title">
                    <label>帮助中心</label>
                    <url>help</url>
                    <title>帮助中心</title>
                    <prepare>true</prepare>
                    <urlParams helper="core/url/getHomeUrl"/>
                    <position>555</position>
                    <liParams/>
                    <!--<aParams>class="top-link-about-us"</aParams>-->
                    <beforeText></beforeText>
                    <afterText></afterText>
                </action>
 
删除:
1、<remove name="checkout_cart_link" />
2、<action method="removeLinkByUrl"><url helper="customer/getAccountUrl"/></action>

16,加载某个 attribute:

$attributeCode=Mage::getModel('catalog/resource_eav_attribute')
->load($attrbuteId)
->getData("attribute_code");
1
2
3
$attributeCode=Mage::getModel('catalog/resource_eav_attribute')
               ->load($attrbuteId)
               ->getData("attribute_code");

17,获取某个 attribute 的所有 option:

$attributeObject=Mage::getModel('eav/config')->getAttribute('catalog_product')->load($attributeId);
$options = $attributeObject->setStoreId(Mage::app()->getStore()->getId())->getSource()->getAllOptions(false);
$table = $attributeObject->getBackend()->getTable();

public function getAttributeOptionsByAttributeCode($entityType, $attributeCode){
$entityType = Mage::getSingleton('eav/config')->getEntityType($entityType);
$attributeObject = Mage::getModel('customer/attribute')->loadByCode($entityType, $attributeCode);
return $attributeObject->setStoreId(Mage::app()->getStore()->getId())->getSource()->getAllOptions(false);
}

或者:
$optionCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attr_model->getId())
->setStoreFilter($storeId, false)->load();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$attributeObject=Mage::getModel('eav/config')->getAttribute('catalog_product')->load($attributeId);
$options = $attributeObject->setStoreId(Mage::app()->getStore()->getId())->getSource()->getAllOptions(false);
$table = $attributeObject->getBackend()->getTable();
 
public function getAttributeOptionsByAttributeCode($entityType, $attributeCode){
$entityType = Mage::getSingleton('eav/config')->getEntityType($entityType);
$attributeObject = Mage::getModel('customer/attribute')->loadByCode($entityType, $attributeCode);
return $attributeObject->setStoreId(Mage::app()->getStore()->getId())->getSource()->getAllOptions(false);
}
 
或者:
$optionCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
    ->setAttributeFilter($attr_model->getId())
    ->setStoreFilter($storeId, false)->load();

18, 获取某个 attribute 的所有多语言 label:

$attributeLabelsArray= Mage::getResourceModel('eav/entity_attribute')->getStoreLabelsByAttributeId($attrbuteId);
1
$attributeLabelsArray= Mage::getResourceModel('eav/entity_attribute')->getStoreLabelsByAttributeId($attrbuteId);

19,获取所有的产品属性的 attribute:

$attributes = Mage::getResourceModel('catalog/product_attribute_collection')->addFieldToFilter("frontend_input","select")->load();
1
$attributes = Mage::getResourceModel('catalog/product_attribute_collection')->addFieldToFilter("frontend_input","select")->load();

20,获取某个 product 的所有 attribute:
注:如果是在collection中获取自定义的attribute,必须加addAttributeToSelect(), 如下:

product=Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect("dropdownlistone");
1
product=Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect("dropdownlistone");

21,利用静态block

<?php echo $this->getLayout()->createBlock('clientnumber/widget_name')->setObject($this->getAddress())->toHtml() ?>
1
<?php echo $this->getLayout()->createBlock('clientnumber/widget_name')->setObject($this->getAddress())->toHtml() ?>

22,获取某个种类的所有 attribute:

$entityTypeId = Mage::getSingleton('eav/config')->getEntityType('catalog_product')->getEntityTypeId();
$items = Mage::getResourceSingleton('catalog/product_attribute_collection')->setEntityTypeFilter($entityTypeId)->getItems();
1
2
$entityTypeId = Mage::getSingleton('eav/config')->getEntityType('catalog_product')->getEntityTypeId();
$items = Mage::getResourceSingleton('catalog/product_attribute_collection')->setEntityTypeFilter($entityTypeId)->getItems();

23,获取某个 attribute_set 的所有 attribute:

$attributes = Mage::getResourceModel('catalog/product_attribute_collection')->setAttributeSetFilter($attribute_set_id)->load();
$attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection')->load();
1
2
$attributes = Mage::getResourceModel('catalog/product_attribute_collection')->setAttributeSetFilter($attribute_set_id)->load();
$attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection')->load();

24,获取 attribute 对象 by attribute code

$muarqspFrom = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'muarqsp_from');
$attrCollection = Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter($attributeCode)->load();
1
2
$muarqspFrom = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'muarqsp_from');
$attrCollection = Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter($attributeCode)->load();

25,get store id

$store_id=Mage::getModel('core/store')
->getCollection()
->addFieldToFilter("code","france_fr")
->getFirstItem()
->getData('store_id');

or
Mage::getModel('core/store')->load('france_fr')->getId();

1
2
3
4
5
6
7
8
$store_id=Mage::getModel('core/store')
->getCollection()
->addFieldToFilter("code","france_fr")
->getFirstItem()
->getData('store_id');
 
or
Mage::getModel('core/store')->load('france_fr')->getId();

26, product collection

$collection = Mage::getResourceModel('catalog/product_collection')
->addStoreFilter()
->addAttributeToSelect("*")
->addAttributeToFilter('entity_id', array('in' => $products))
->setPageSize(10)
->setCurPage(1);
1
2
3
4
5
6
$collection = Mage::getResourceModel('catalog/product_collection')
->addStoreFilter()
->addAttributeToSelect("*")
->addAttributeToFilter('entity_id', array('in' => $products))
->setPageSize(10)
->setCurPage(1);

27,数据库操作

$dbr = Mage::getSingleton('core/resource')->getConnection('core_read');
$sql = "select instructor_id,position from product_instructor_link where product_id = $productId";
$result = $dbr->fetchAll($sql);
//$result = $dbr->fetchOne($sql);
$instructors = array();
foreach($result as $item){
$instructors[$item['instructor_id']] = array('position' => $item['position']);
}

$dbw = Mage::getSingleton('core/resource')->getConnection('core_write');
$sql="update catalog_product_entity_datetime set value=NULL where attribute_id=$special_from_date_attribute_id and store_id=$storeId and entity_id=$productId";
$dbw->query( $sql );

1
2
3
4
5
6
7
8
9
10
11
12
$dbr = Mage::getSingleton('core/resource')->getConnection('core_read');
$sql = "select instructor_id,position from product_instructor_link where product_id = $productId";
$result = $dbr->fetchAll($sql);
//$result = $dbr->fetchOne($sql);
$instructors = array();
foreach($result as $item){
$instructors[$item['instructor_id']] = array('position' => $item['position']);
}
 
$dbw = Mage::getSingleton('core/resource')->getConnection('core_write');
$sql="update catalog_product_entity_datetime set value=NULL where attribute_id=$special_from_date_attribute_id and store_id=$storeId and entity_id=$productId";
$dbw->query( $sql );

28,获取 quote 中的所有的 item

$quote=Mage::getSingleton('checkout/session')->getQuote();
foreach ($quote->getAllItems() as $item) {
$proId[]=$item->getProduct()->getId();
}
1
2
3
4
$quote=Mage::getSingleton('checkout/session')->getQuote();
foreach ($quote->getAllItems() as $item) {
$proId[]=$item->getProduct()->getId();
}

29,获取这个网站所代表的国家的代号(如:FR)

Mage::getModel('directory/country')->load(Mage::getStoreConfig('general/country/default'))->getIso2Code()
1
Mage::getModel('directory/country')->load(Mage::getStoreConfig('general/country/default'))->getIso2Code()

30,获取后台的配置

Mage::getStoreConfig("clientnumber/total_config/service_ip",0); //get admin config
1
Mage::getStoreConfig("clientnumber/total_config/service_ip",0); //get admin config

31,获取当前的时间

$date = Mage::app()->getLocale()->date(Mage::getSingleton('core/date')->gmtTimestamp(), null, null);
$date = $date->toString('yyyy-MM-dd hh:m:s');
1
2
$date = Mage::app()->getLocale()->date(Mage::getSingleton('core/date')->gmtTimestamp(), null, null);
$date = $date->toString('yyyy-MM-dd hh:m:s');

32,generate skin url

Mage::getDesign()->getSkinUrl('images/our_shops/shop_logo_default
1
Mage::getDesign()->getSkinUrl('images/our_shops/shop_logo_default

33,generate select html

$html = $this->getLayout()->createBlock('core/html_select')
->setName($name)
->setId($id)
->setTitle(Mage::helper('directory')->__($title))
->setClass('validate-select')
->setValue($defValue)
->setOptions($options)
->getHtml();
1
2
3
4
5
6
7
8
$html = $this->getLayout()->createBlock('core/html_select')
->setName($name)
->setId($id)
->setTitle(Mage::helper('directory')->__($title))
->setClass('validate-select')
->setValue($defValue)
->setOptions($options)
->getHtml();

34,删除一个product的所有的images

//Get products gallery attribute
$attributes = $product->getTypeInstance()->getSetAttributes();

if (isset($attributes['media_gallery'])) {
$gallery = $attributes['media_gallery'];
//Get the images
$galleryData = $product->getMediaGallery();

foreach($galleryData['images'] as $image){
//If image exists
if ($gallery->getBackend()->getImage($product, $image['file'])) {
$gallery->getBackend()->removeImage($product, $image['file']);
$filename = Mage::getBaseDir('media').DS.'catalog'.DS.'product'.$image['file'];
debug('<span style="color: green;">&lt;&lt; unlinked previous image '.$image['file'].' from product '.$product->getSku().'</span>');
if (file_exists($filename) && is_file($filename) && is_writeable($filename)){
@unlink($filename);
debug('<span style="color: green;">(and deleted file '.$filename.')</span>');
}else
debug('<span style="color: red;">(but couldn\'t delete file '.$filename.')</span>');
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Get products gallery attribute
$attributes = $product->getTypeInstance()->getSetAttributes();
 
if (isset($attributes['media_gallery'])) {
$gallery = $attributes['media_gallery'];
//Get the images
$galleryData = $product->getMediaGallery();
 
foreach($galleryData['images'] as $image){
//If image exists
if ($gallery->getBackend()->getImage($product, $image['file'])) {
$gallery->getBackend()->removeImage($product, $image['file']);
$filename = Mage::getBaseDir('media').DS.'catalog'.DS.'product'.$image['file'];
debug('<span style="color: green;">&lt;&lt; unlinked previous image '.$image['file'].' from product '.$product->getSku().'</span>');
if (file_exists($filename) && is_file($filename) && is_writeable($filename)){
@unlink($filename);
debug('<span style="color: green;">(and deleted file '.$filename.')</span>');
}else
debug('<span style="color: red;">(but couldn\'t delete file '.$filename.')</span>');
}
}
}

35,获取指定level目录

$parent = Mage::app()->getStore()->getRootCategoryId();
$categoryModel = Mage::getModel('catalog/category');
$storeCategories = $categoryModel->getCategories($parent, 2); //获取level 2
1
2
3
$parent = Mage::app()->getStore()->getRootCategoryId();
$categoryModel = Mage::getModel('catalog/category');
$storeCategories = $categoryModel->getCategories($parent, 2); //获取level 2

36,发送邮件

$mailTransport = new Zend_Mail_Transport_Smtp('192.168.0.1');
$mail = new Zend_Mail();
$mail->setBodyText($content);
$mail->setFrom("hello@example.com", 'Webmaster');
$mail->addTo("bysoftgz@gmail.com", '');
$mail->setSubject('Import attribute logs');
$mail->send($mailTransport);
1
2
3
4
5
6
7
$mailTransport = new Zend_Mail_Transport_Smtp('192.168.0.1');
$mail = new Zend_Mail();
$mail->setBodyText($content);
$mail->setFrom("hello@example.com", 'Webmaster');
$mail->addTo("bysoftgz@gmail.com", '');
$mail->setSubject('Import attribute logs');
$mail->send($mailTransport);

37, get website config

//$website can be string or id
$import_type = Mage::getModel('core/website')->load($website)->getConfig('maps/stock_import/stock_limit');
if( $import_type===false ){
//get admin config
$import_type=Mage::getStoreConfig('maps/stock_import/import_type',0);
}
1
2
3
4
5
6
//$website can be string or id
$import_type = Mage::getModel('core/website')->load($website)->getConfig('maps/stock_import/stock_limit');
if( $import_type===false ){
//get admin config
$import_type=Mage::getStoreConfig('maps/stock_import/import_type',0);
}

38,用block创建一个template

<?php echo Mage::getBlockSingleton('inseecode/form')->getInseeFormHtml($this->getAddress(), 'customer');?>
public function getInseeFormHtml($address, $type) {
$this->setTemplate('inseecode/form.phtml');
return $this->toHtml();
}
1
2
3
4
5
<?php echo Mage::getBlockSingleton('inseecode/form')->getInseeFormHtml($this->getAddress(), 'customer');?>
public function getInseeFormHtml($address, $type) {
$this->setTemplate('inseecode/form.phtml');
return $this->toHtml();
}

39,
获取对象的方法: get_class_methods($object)
返回对象的类名: get_class($object)

40,controller 中 添加block

$this->getLayout()
->createBlock('clientnumber/inputform', 'checkout.cart.inputclientnumber')
->setTemplate('clientnumber/input.phtml')
->toHtml()
1
2
3
4
$this->getLayout()
->createBlock('clientnumber/inputform', 'checkout.cart.inputclientnumber')
->setTemplate('clientnumber/input.phtml')
->toHtml()

41,在Configuation中添加validate

<validate>validate-number</validate>
1
<validate>validate-number</validate>

42, 获取当前的controller

$moduleName=Mage::app()->getRequest()->getModuleName();
$controllerName=Mage::app()->getRequest()->getControllerName();
$actionName=Mage::app()->getRequest()->getActionName();
$fullActionName=$moduleName."_".$controllerName."_".$actionName;
1
2
3
4
$moduleName=Mage::app()->getRequest()->getModuleName();
$controllerName=Mage::app()->getRequest()->getControllerName();
$actionName=Mage::app()->getRequest()->getActionName();
$fullActionName=$moduleName."_".$controllerName."_".$actionName;

43, can't see load.gif in firefox6
so just remove or comment the id "#loading-mas" about ,it will solve it

44,get attributeSetId by attributeName

Mage::getResourceModel('eav/entity_attribute_set_collection')
->addFieldToFilter('attribute_set_name',$attributSetName)
->getFirstItem()->getId();
1
2
3
Mage::getResourceModel('eav/entity_attribute_set_collection')
->addFieldToFilter('attribute_set_name',$attributSetName)
->getFirstItem()->getId();

45,get attributeSetName by attributeSetId

Mage::getModel('eav/entity_attribute_set')->load($id)->getData("attribute_set_name");
1
Mage::getModel('eav/entity_attribute_set')->load($id)->getData("attribute_set_name");

46,修改数据库结构

$installer->getConnection()->addColumn(
$installer->getTable('enterprise_giftcardaccount/giftcardaccount'),
'gift_card_type',
"VARCHAR(200) DEFAULT ''");

$installer->getConnection()->addColumn(
$installer->getTable('enterprise_giftcardaccount/giftcardaccount'),
'gift_card_type',
"TINYINT(1) UNSIGNED NOT NULL DEFAULT '0'");

$installer->getConnection()->dropColumn($installer->getTable('eav_attribute'), 'use_in_super_product');
$installer->run("ALTER TABLE [crayon-57a13b78c90ba958629555 inline="true" ]sales_flat_order

1
2
3
4
5
6
7
8
9
10
11
12
$installer->getConnection()->addColumn(
$installer->getTable('enterprise_giftcardaccount/giftcardaccount'),
'gift_card_type',
"VARCHAR(200) DEFAULT ''");
 
$installer->getConnection()->addColumn(
$installer->getTable('enterprise_giftcardaccount/giftcardaccount'),
'gift_card_type',
"TINYINT(1) UNSIGNED NOT NULL DEFAULT '0'");
 
$installer->getConnection()->dropColumn($installer->getTable('eav_attribute'), 'use_in_super_product');
$installer->run("ALTER TABLE [crayon-57a13b78c90ba958629555 inline="true" ]sales_flat_order

CHANGE is_synced is_synced INT(4) NOT NULL");
[/crayon]

47,获取登录的用户信息

Mage::getSingleton('customer/session')->getCustomer()
1
Mage::getSingleton('customer/session')->getCustomer()

48,格式化时间

Mage::app()->getLocale()->date($creditMemo->getCreatedAt())->toString('YYYY-MM-dd');
或:
$this->_filterDates($data, array('date_expires'));
protected function _filterDates($array, $dateFields)
{
if (empty($dateFields)) {
return $array;
}
$filterInput = new Zend_Filter_LocalizedToNormalized(array('date_format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT)));
$filterInternal = new Zend_Filter_NormalizedToLocalized(array('date_format' => Varien_Date::DATE_INTERNAL_FORMAT));
foreach ($dateFields as $dateField) {
if (array_key_exists($dateField, $array) && !empty($dateField)) {
$array[$dateField] = $filterInput->filter($array[$dateField]);
$array[$dateField] = $filterInternal->filter($array[$dateField]);
}
}
return $array;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Mage::app()->getLocale()->date($creditMemo->getCreatedAt())->toString('YYYY-MM-dd');
或:
$this->_filterDates($data, array('date_expires'));
protected function _filterDates($array, $dateFields)
    {
    if (empty($dateFields)) {
        return $array;
    }
    $filterInput = new Zend_Filter_LocalizedToNormalized(array('date_format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT)));
    $filterInternal = new Zend_Filter_NormalizedToLocalized(array('date_format' => Varien_Date::DATE_INTERNAL_FORMAT));
    foreach ($dateFields as $dateField) {
        if (array_key_exists($dateField, $array) && !empty($dateField)) {
        $array[$dateField] = $filterInput->filter($array[$dateField]);
        $array[$dateField] = $filterInternal->filter($array[$dateField]);
        }
    }
    return $array;
    }

49,加减日期

Mage::app()->getLocale()->date()->sub("3",Zend_Date::DAY)->toString('YYYY-MM-dd HH:mm:ss');
1
Mage::app()->getLocale()->date()->sub("3",Zend_Date::DAY)->toString('YYYY-MM-dd HH:mm:ss');

50, 打印php调试信息的代码

$array = debug_backtrace();
//print_r($array);//信息很齐全
unset($array[0]);
foreach($array as $row)
{
$html .= $row['file'].':'.$row['line'].'行,调用方法:'.$row['function']."<p>";
}
echo $html;
exit();
1
2
3
4
5
6
7
8
9
$array = debug_backtrace();
//print_r($array);//信息很齐全
unset($array[0]);
foreach($array as $row)
{
$html .= $row['file'].':'.$row['line'].'行,调用方法:'.$row['function']."<p>";
}
echo $html;
exit();

51,添加面包翘
在 controller中:

$this->loadLayout();
$breadCrumb = $this->getLayout()->getBlock('breadcrumbs');
$breadCrumb->addCrumb('home', array(
'label' => Mage::helper('catalog')->__('Home'),
'title' => Mage::helper('catalog')->__('Go to Home Page'),
'link' => Mage::getBaseUrl(),
))->addCrumb('youhui', array(
'label' => Mage::helper('catalog')->__('youhuihuodong'),
'title' => Mage::helper('catalog')->__('youhuihuodong'),
'link' => $category->getId() ? Mage::getUrl('*/*') : NULL,
));
1
2
3
4
5
6
7
8
9
10
11
$this->loadLayout();
$breadCrumb = $this->getLayout()->getBlock('breadcrumbs');
$breadCrumb->addCrumb('home', array(
'label' => Mage::helper('catalog')->__('Home'),
'title' => Mage::helper('catalog')->__('Go to Home Page'),
'link'  => Mage::getBaseUrl(),
))->addCrumb('youhui', array(
'label' => Mage::helper('catalog')->__('youhuihuodong'),
'title' => Mage::helper('catalog')->__('youhuihuodong'),
'link'  => $category->getId() ? Mage::getUrl('*/*') : NULL,
));

52,filter in collection

$collection = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('status', array('eq'=>'pending'))
->addFieldToFilter('created_at', array('datetime' => true, 'from'=>"2011-10-10 00:00:00",'to' => Mage::app()->getLocale()->date()->sub("3",Zend_Date::DAY)->toString('YYYY-MM-dd HH:mm:ss')));
1
2
3
$collection = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('status', array('eq'=>'pending'))
->addFieldToFilter('created_at', array('datetime' => true, 'from'=>"2011-10-10 00:00:00",'to' => Mage::app()->getLocale()->date()->sub("3",Zend_Date::DAY)->toString('YYYY-MM-dd HH:mm:ss')));

53,日期过滤

$todayDate = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$this->_getProductCollection()
->addAttributeToFilter('news_from_date', array('or'=> array(
0 => array('date' => true, 'to' => $todayDate),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left')
->addAttributeToFilter('news_to_date', array('or'=> array(
0 => array('date' => true, 'from' => $todayDate),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left')
->addAttributeToFilter(
array(
array('attribute' => 'news_from_date', 'is'=>new Zend_Db_Expr('not null')),
array('attribute' => 'news_to_date', 'is'=>new Zend_Db_Expr('not null'))
)
)
->addAttributeToFilter('visibility', array('in' => array(2, 4)))
->addAttributeToSort('news_from_date', 'desc')
->setPage(1, 4);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$this->_getProductCollection()
->addAttributeToFilter('news_from_date', array('or'=> array(
0 => array('date' => true, 'to' => $todayDate),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left')
->addAttributeToFilter('news_to_date', array('or'=> array(
0 => array('date' => true, 'from' => $todayDate),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left')
->addAttributeToFilter(
array(
array('attribute' => 'news_from_date', 'is'=>new Zend_Db_Expr('not null')),
array('attribute' => 'news_to_date', 'is'=>new Zend_Db_Expr('not null'))
)
)
->addAttributeToFilter('visibility', array('in' => array(2, 4)))
->addAttributeToSort('news_from_date', 'desc')
->setPage(1, 4);

54,判断日期是否有效

Mage::app()->getLocale()->isStoreDateInInterval(Mage::app()->getStore(), $special_from_date, $special_to_date)
1
Mage::app()->getLocale()->isStoreDateInInterval(Mage::app()->getStore(), $special_from_date, $special_to_date)

55,test code for quote

$quote=Mage::getSingleton('checkout/session')->getQuote();
foreach ($quote->getAllVisibleItems() as $item) {
echo $item->getProductId();
}
$quote->collectTotals()->save();
1
2
3
4
5
$quote=Mage::getSingleton('checkout/session')->getQuote();
foreach ($quote->getAllVisibleItems() as $item) {
echo $item->getProductId();
}
$quote->collectTotals()->save();

56,日期的比较

//get orders 15 days ago
$collection = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('status', array('eq' => 'pending'))
->addFieldToFilter('created_at', array('datetime' => true, 'from' => "2011-10-10 00:00:00", 'to' => Mage::app()->getLocale()
->date()
->sub("15", Zend_Date::DAY)
->toString('YYYY-MM-dd HH:mm:ss'))
);
1
2
3
4
5
6
7
8
//get orders 15 days ago
$collection = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('status', array('eq' => 'pending'))
->addFieldToFilter('created_at', array('datetime' => true, 'from' => "2011-10-10 00:00:00", 'to' => Mage::app()->getLocale()
->date()
->sub("15", Zend_Date::DAY)
->toString('YYYY-MM-dd HH:mm:ss'))
);

57,delete confirm js

function confirmSetLocation(message, url){
if( confirm(message) ) {
setLocation(url);
}
return false;
}

function setLocation(url){
window.location.href = url;
}

1
2
3
4
5
6
7
8
9
10
function confirmSetLocation(message, url){
if( confirm(message) ) {
setLocation(url);
}
return false;
}
 
function setLocation(url){
window.location.href = url;
}

58, 在controller中返回blocl html

$this->getResponse()->setBody($this->getLayout()->createBlock('invoicebill/account_content')
->setTemplate("bysoft/invoicebill/account/content.phtml")
->toHtml());
1
2
3
$this->getResponse()->setBody($this->getLayout()->createBlock('invoicebill/account_content')
->setTemplate("bysoft/invoicebill/account/content.phtml")
->toHtml());

59,获取某个action的url

Mage::getUrl('checkout/process/directOver', array('_secure'=>true));
1
Mage::getUrl('checkout/process/directOver', array('_secure'=>true));

60, 添加customer attribute

$installer = $this;
$installer->startSetup();
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$entityTypeId = $setup->getEntityTypeId('customer_address');
$attributeSetId = $setup->getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $setup->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);

/* add customer address attribute "mobile" */
$installer->addAttribute('customer_address', 'mobile1',array(
'label' => 'Mobile',
'type' => 'varchar',
'input' => 'text',
'used_in_forms' => array('customer_register_address','customer_address_edit'),
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => true,
'user_defined' => true,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => true,
'visible_in_advanced_search' => false,
'unique' => false
));

$setup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attributeGroupId,
'mobile1',
'200' //sort_order
);

$installer->endSetup();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
$installer = $this;
$installer->startSetup();
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$entityTypeId     = $setup->getEntityTypeId('customer_address');
$attributeSetId   = $setup->getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $setup->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);
 
/* add customer address attribute "mobile" */
$installer->addAttribute('customer_address', 'mobile1',array(
'label' => 'Mobile',
'type' => 'varchar',
'input' => 'text',
'used_in_forms' => array('customer_register_address','customer_address_edit'),
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => true,
'user_defined' => true,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => true,
'visible_in_advanced_search' => false,
'unique' => false
));
 
$setup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attributeGroupId,
'mobile1',
'200'  //sort_order
);
 
$installer->endSetup();

61,获取product某个 option的label

public function getProductOptionLable( $optionid=0 )
{
$tableName = Mage::getSingleton('core/resource')->getTableName('eav_attribute_option_value');
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$storeid = Mage::app()->getStore()->getId();
if($optionid)
{
$sql="select value from $tableName where option_id=$optionid and store_id=$storeid";
$query=$read->query($sql);
$row = $query->fetch();

//if can't get value from default store view, then get data from admin store view
if(trim($row['value'])=="" {
$sql="select value from $tableName where option_id=$optionid and store_id=0";
$query=$read->query($sql);
$row = $query->fetch();
}
}
else
{
$row=array('value'=>'');
}
return $row['value'];
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public function getProductOptionLable( $optionid=0 )
{
$tableName = Mage::getSingleton('core/resource')->getTableName('eav_attribute_option_value');
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$storeid = Mage::app()->getStore()->getId();
if($optionid)
{
$sql="select value from $tableName where option_id=$optionid and store_id=$storeid";
$query=$read->query($sql);
$row = $query->fetch();
 
//if can't get value from default store view, then get data from admin store view
if(trim($row['value'])=="" {
$sql="select value from $tableName where option_id=$optionid and store_id=0";
$query=$read->query($sql);
$row = $query->fetch();
}
}
else
{
$row=array('value'=>'');
}
return  $row['value'];
}

62, 格式化某个日期

Mage::app()->getLocale()->date($_obj->getCreatedAt(), null, null)->toString('yyyy.MM.dd');
1
Mage::app()->getLocale()->date($_obj->getCreatedAt(), null, null)->toString('yyyy.MM.dd');

63,magento中只单独保存某个attribute的方法

$order->setData('customer_email',$address->getData("email"));
$order->getResource()->saveAttribute($order, 'customer_email');
1
2
$order->setData('customer_email',$address->getData("email"));
$order->getResource()->saveAttribute($order, 'customer_email');

64,常用的load

PHP
Mage::getModel('sales/order')->load();
Mage::getModel('customer/customer')->load();
Mage::getModel('catalog/product')->load();
1
2
3
Mage::getModel('sales/order')->load();
Mage::getModel('customer/customer')->load();
Mage::getModel('catalog/product')->load();

magento 常用方法集锦的更多相关文章

  1. jQuery常用方法集锦

    用方法:http://www.cnblogs.com/linzheng/archive/2010/11/14/1877092.html 数组汇总:http://www.cnblogs.com/Andy ...

  2. commons-lang 包常用方法

      package com.java.utils; import java.util.Iterator; import java.util.Map;   import org.apache.commo ...

  3. vue vuex初学基础 常见错误解决方式

    前端界面使用篇 vue生命周期初始化事件 http://www.cnblogs.com/lily1010/p/5830946.html 常见错误篇 1 Newline required at end ...

  4. Magento开发常用方法

    这里是我做Magento开发常用到的方法,现在总结出来,后续会把更多有用的方法总结出来. 1.直接操作数据库 查找数据:$read = Mage::getSingleton("core/re ...

  5. crawler_java应用集锦9:httpclient4.2.2的几个常用方法,登录之后访问页面问题,下载文件_设置代理

    在工作中要用到android,然后进行网络请求的时候,打算使用httpClient. 总结一下httpClient的一些基本使用. 版本是4.2.2. 使用这个版本的过程中,百度很多,结果都是出现的o ...

  6. java应用集锦9:httpclient4.2.2的几个常用方法,登录之后访问页面问题,下载文件

    转账注明出处:http://renjie120.iteye.com/blog/1727933 在工作中要用到android,然后进行网络请求的时候,打算使用httpClient. 总结一下httpCl ...

  7. JAVA工程师面试常见问题集锦

    集锦一: 一.面试题基础总结 1. JVM结构原理.GC工作机制详解 答:具体参照:JVM结构.GC工作机制详解     ,说到GC,记住两点:1.GC是负责回收所有无任何引用对象的内存空间. 注意: ...

  8. Redis面试题集锦(精选)

    1.什么是 Redis?简述它的优缺点? Redis的全称是:Remote Dictionary.Server,本质上是一个Key-Value 类型的内存数据库,很像memcached,整个数据库统统 ...

  9. 看完SQL Server 2014 Q/A答疑集锦:想不升级都难!

    看完SQL Server 2014 Q/A答疑集锦:想不升级都难! 转载自:http://mp.weixin.qq.com/s/5rZCgnMKmJqeC7hbe4CZ_g 本期嘉宾为微软技术中心技术 ...

随机推荐

  1. 【转】Android 4.4源码下载与编译

    原文网址:http://www.cnblogs.com/zhx831/p/3550830.html 这篇文章记录了我下载源码和编译的全过程, 全过程参考Android官方文档 1. 下载Android ...

  2. 用css控制cellspacing、cellpadding

    用css控制cellspacing.cellpadding 发表于 2006 年 12 月 24 日 由 Silbo 在table中控制单元格之间的间距要用到cellspacing.cellpaddi ...

  3. Android开发视频学习(1)

    S01E02_搭建Android开发环境 设置ANDROID_SDK_HOME环境变量,用于指定Android模拟器的目录,官方文档没有说要设置. S01E03_Android创世纪 Android根 ...

  4. python __enter__ 与 __exit__的作用,以及与 with 语句的关系

    转载自:http://linbo.github.io/2013/01/08/python-with/ (一直不知道博客园哪里发转载文章) With语句是什么? 有一些任务,可能事先需要设置,事后做清理 ...

  5. 终于写好了SR4000的一个实用类了

    /*----------------------------------------------------------------------------- *   *   版权声明: *   可以 ...

  6. VellCar(我的钢管车)

    我自己设计了一款钢管车,由于绘图水平有限,所以做的不是特别好看,但整个车架都是我自己设计的,个人觉得不错,尺寸也是按着实际尺寸做的,长2.5米宽为1米,后置发动机,后驱...贴图吧,更形象: 所有零部 ...

  7. HW2.24

    import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner i ...

  8. 获取所有组合算法、获取全排列算法(java)

    转载声明:原文转自:http://www.cnblogs.com/xiezie/p/5574516.html 受到ACM1015的影响,个人感觉,有必要对统计学上的 全组合和全排列 进行一个简单的总结 ...

  9. Codeforces Round #311 (Div. 2) D - Vitaly and Cycle(二分图染色应用)

    http://www.cnblogs.com/wenruo/p/4959509.html 给一个图(不一定是连通图,无重边和自环),求练成一个长度为奇数的环最小需要加几条边,和加最少边的方案数. 很容 ...

  10. 框架技术--S2SH框架整合(spring部分)No 3--声明式事务

    声明式事务:就是讲事务的处理,通过配置进行配置. 几种传播特性  1. PROPAGATION_REQUIRED: 如果存在一个事务,则支持当前事务.如果没有事务则开启(比较常用)  2. PROPA ...