magento常用方法集锦

1,获得store的配置变量

1
2

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

2,设置store的配置变量

1
2

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,快捷格式化商品价格

1
2

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

6,格式化时间

1
2
3
4
5
6
7

原始日期: <?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

1
2
3

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

8,用户中心菜单增删改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

删除:
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

1
2
3
4

增加:<?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:

1
2
3
4
5
6

// 返回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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

$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;&#038; $totals['discount']->getValue()) {
$discount = round($totals['discount']->getValue()); //Discount value if applied
} else {
$discount = '';
}
if(isset($totals['tax']) &#038;&#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 – 获取订单支付信息:

1
2
3
4

$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,获取网站基本信息:

1
2
3
4
5

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,获取订单状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

$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') ?>
![](<?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()): ?>

<?php echo $this->escapeHtml($_item->getComment(), array('b','br','strong','i','u')) ?>
<?php endif; ?>
<?php endforeach; ?>

15,top.link的添加删除:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

添加:
<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:

1
2
3
4

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

$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:

1
2

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

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

1
2

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

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

1
2

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

21,利用静态block

1
2

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

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

1
2
3

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

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

1
2
3

$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

1
2
3

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

25,get store id

1
2
3
4
5
6
7
8
9

$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

1
2
3
4
5
6
7

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

27,数据库操作

1
2
3
4
5
6
7
8
9
10
11
12
13

$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

1
2
3
4
5

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

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

1
2

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

30,获取后台的配置

1
2

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

31,获取当前的时间

1
2
3

$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

1
2

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

33,generate select html

1
2
3
4
5
6
7
8
9

$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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

//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;"><< 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目录

1
2
3
4

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

36,发送邮件

1
2
3
4
5
6
7
8

$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

1
2
3
4
5
6
7

//$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

1
2
3
4
5
6

<?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

1
2
3
4
5

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

41,在Configuation中添加validate

1
2

<validate>validate-number</validate>

42, 获取当前的controller

1
2
3
4
5

$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

1
2
3
4

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

45,get attributeSetName by attributeSetId

1
2

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

46,修改数据库结构

1
2
3
4
5
6
7
8
9
10
11
12
13

$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 `sales_flat_order` CHANGE `is_synced` `is_synced` INT(4) NOT NULL");

47,获取登录的用户信息

1
2

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

48,格式化时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

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,加减日期

1
2

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

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

1
2
3
4
5
6
7
8
9
10

$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中:

1
2
3
4
5
6
7
8
9
10
11
12

$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

1
2
3
4

$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,日期过滤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

$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,判断日期是否有效

1
2

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

55,test code for quote

1
2
3
4
5
6

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

56,日期的比较

1
2
3
4
5
6
7
8
9

//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

1
2
3
4
5
6
7
8
9
10
11

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

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

58, 在controller中返回blocl html

1
2
3
4

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

59,获取某个action的url

1
2

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

60, 添加customer attribute

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
36

$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

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

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, 格式化某个日期

1
2

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

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

1
2
3

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

64,常用的load

1
2
3
4

Mage::getModel('sales/order')->load();
Mage::getModel('customer/customer')->load();
Mage::getModel('catalog/product')->load();
坚持原创技术分享,您的支持将鼓励我继续创作!