magento中的一些技巧
1.加载某个attribute:
$attributeCode=Mage::getModel('catalog/resource_eav_attribute')
->load($attrbuteId)
->getData("attribute_code");
2.获取某个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();
3.获取某个attribute的所有多语言label:
$attributeLabelsArray= Mage::getResourceModel('eav/entity_attribute')
->getStoreLabelsByAttributeId($attrbuteId);
4.获取所有的产品属性的attribute:
$attributes = Mage::getResourceModel ( 'catalog/product_attribute_collection' )
->addFieldToFilter ( "frontend_input", "select" )
->load ();
5.获取某个product的所有attribute:
注:如果是在collection中获取自定义的attribute,必须加addAttributeToSelect(), 如下:
product=Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect("dropdownlistone");
6.利用静态block
<?php echo $this->getLayout()->createBlock('clientnumber/widget_name')
->setObject($this->getAddress())
->toHtml() ?>
7.获取某个种类的所有attribute:
$entityTypeId = Mage::getSingleton('eav/config')
->getEntityType('catalog_product')
->getEntityTypeId();
$items = Mage::getResourceSingleton('catalog/product_attribute_collection')
->setEntityTypeFilter($entityTypeId)
->getItems();
8.获取某个attribute_set的所有attribute:
$attributes = Mage::getResourceModel('catalog/product_attribute_collection')
->setAttributeSetFilter($attribute_set_id)
->load();
$attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection')
->load();
9.获取attribute 对象 by attribute code
$muarqspFrom = Mage::getSingleton('eav/config')->getAttribute('catalog_product', '
muarqsp_from');
$attrCollection = Mage::getResourceModel('eav/entity_attribute_collection')
->setCodeFilter($attributeCode)
->load();
10。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();
11.product collection
$collection = Mage::getResourceModel('catalog/product_collection')
->addStoreFilter()
->addAttributeToSelect("*")
->addAttributeToFilter('entity_id', array('in' => $products))
->setPageSize(10)
->setCurPage(1);
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 );
13. 获取quote中的所有的item
$quote=Mage::getSingleton('checkout/session')->getQuote();
foreach ($quote->getAllItems() as $item) {
$proId[]=$item->getProduct()->getId();
}
14. 获取这个网站所代表的国家的代号(如:FR)
Mage::getModel('directory/country')
->load(Mage::getStoreConfig('general/country/default'))->getIso2Code(),
15. 获取后台的配置
Mage::getStoreConfig("clientnumber/total_config/service_ip",0); //get admin config
16. 获取当前的时间
$date = Mage::app()->getLocale()->date(Mage::getSingleton('core/date')->gmtTimestamp(), null, null);
$date = $date->toString('yyyy-MM-dd hh:m:s');
17. generate skin url
Mage::getDesign()->getSkinUrl('images/our_shops/shop_logo_default.jpg');
18. 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();
19. 删除一个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;"><< 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>');
}
}
}
20. 获取指定level目录
$parent = Mage::app()->getStore()->getRootCategoryId();
$categoryModel = Mage::getModel('catalog/category');
$storeCategories = $categoryModel->getCategories($parent, 2); //获取level 2
21. 发送邮件
$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);
22.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);
}
23. 用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();
}
24.
获取对象的方法:get_class_methods($object)
返回对象的类名:get_class($object)
25. controller 中 添加block
$this->getLayout()
->createBlock('clientnumber/inputform', 'checkout.cart.inputclientnumber')
->setTemplate('clientnumber/input.phtml')
->toHtml()
26. 在Configuation中添加validate
<validate>validate-number</validate>
27. 获取当前的controller
$moduleName=Mage::app()->getRequest()->getModuleName();
$controllerName=Mage::app()->getRequest()->getControllerName();
$actionName=Mage::app()->getRequest()->getActionName();
$fullActionName=$moduleName."_".$controllerName."_".$actionName;
28. can't see load.gif in firefox6
so just remove or comment the id "#loading-mas" about <!-- opacity: 0.8;-->,it will solve it
29. get attributeSetId by attributeName
Mage::getResourceModel('eav/entity_attribute_set_collection')
->addFieldToFilter('attribute_set_name',$attributSetName)
->getFirstItem()->getId();
30. get attributeSetName by attributeSetId
Mage::getModel('eav/entity_attribute_set')
->load($id)->getData("attribute_set_name");
31.修改数据库结构
$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 ");
32. 获取登录的用户信息
Mage::getSingleton('customer/session')->getCustomer()
33. 格式化时间
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;
}
34. 加减日期
Mage::app()->getLocale()->date()->sub("3",Zend_Date::DAY)->toString('YYYY-MM-dd HH:mm:ss');
35. 打印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();
36.添加面包翘
在 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,
))
;
37. 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')));
38. 日期过滤
$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)
;
39. 判断日期是否有效
Mage::app()->getLocale()->isStoreDateInInterval(Mage::app()->getStore(), $special_from_date, $special_to_date)
40.test code for quote
$quote=Mage::getSingleton('checkout/session')->getQuote();
foreach ($quote->getAllVisibleItems() as $item) {
echo $item->getProductId();
}
$quote->collectTotals()->save();
40.日期的比较
//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'))
)
;
41. delete confirm js
function confirmSetLocation(message, url){
if( confirm(message) ) {
setLocation(url);
}
return false;
}
function setLocation(url){
window.location.href = url;
}
42.在controller中返回blocl html
$this->getResponse()->setBody($this->getLayout()->createBlock('invoicebill/account_content')
->setTemplate("bysoft/invoicebill/account/content.phtml")
->toHtml());
43. 获取某个action的url
Mage::getUrl('checkout/process/directOver', array('_secure'=>true));
44. 添加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();
45. 获取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'];
}
46. 格式化某个日期
Mage::app()->getLocale()->date($_obj->getCreatedAt(), null, null)->toString('yyyy.MM.dd');
47.magento中只单独保存某个attribute的方法
$order->setData('customer_email',$address->getData("email"));
$order->getResource()->saveAttribute($order, 'customer_email');
48. 常用的load
Mage::getModel('sales/order')->load();
Mage::getModel('customer/customer')->load();
Mage::getModel('catalog/product')->load();
magento中的一些技巧的更多相关文章
- ios开发中的小技巧
在这里总结一些iOS开发中的小技巧,能大大方便我们的开发,持续更新. UITableView的Group样式下顶部空白处理 //分组列表头部空白处理 UIView *view = [[UIViewal ...
- 背水一战 Windows 10 (21) - 绑定: x:Bind 绑定, x:Bind 绑定之 x:Phase, 使用绑定过程中的一些技巧
[源码下载] 背水一战 Windows 10 (21) - 绑定: x:Bind 绑定, x:Bind 绑定之 x:Phase, 使用绑定过程中的一些技巧 作者:webabcd 介绍背水一战 Wind ...
- 绑定: x:Bind 绑定, x:Bind 绑定之 x:Phase, 使用绑定过程中的一些技巧
背水一战 Windows 10 之 绑定 x:Bind 绑定 x:Bind 绑定之 x:Phase 使用绑定过程中的一些技巧 示例1.演示 x:Bind 绑定的相关知识点Bind/BindDemo.x ...
- iOS开发中调试小技巧
对于软件开发而言,调试是必须学会的技能,重要性不言而喻.对于调试的技能,基本上是可以迁移的,也就是说你以前在其他平台上掌握的很多调试技巧,很多也是可以用在iOS开发中.不同语言.不同IDE.不同平台的 ...
- IOS中图片拉伸技巧与方法总结(转载)
以下内容转载自:http://my.oschina.net/u/2340880/blog/403996 IOS中图片拉伸技巧与方法总结 一.了解几个图像拉伸的函数和方法 1.直接拉伸法 简单暴力,却是 ...
- 在magento中如何回复客户的评论
magento — 在magento中如何回复客户的评论 发表于 2012 年 8 月 18 日 agento本身是不带 回复评论的功能的,现成的扩展(无论免费的还是商业的)也没找到,那就自己写一个吧 ...
- Magento中,调用静态块的几种方法
在后台创建一个order_form静态块Block Title :Order FormIdentifier :order_formStatus :EnabledContent :自定义内容 1.如果要 ...
- Magento中直接使用SQL语句
原理: magento是基于Zend Framework的,所以底层用的还是zend的zend db 在文件app/code/core/Mage/Catalog/model/Resource/Eav ...
- Magento 中的多个类别的筛选产品集合
通过在 Magento 中的多个类别的筛选产品集合. 按只 1 类别筛选 Magento 提供筛选器,可以使用直接从该集合的类型: $_category = Mage::getModel('catal ...
随机推荐
- AlarmManager用法
源http://blog.csdn.net/wangxingwu_314/article/details/8060312
- Android增量更新
http://blog.csdn.net/tu_bingbing/article/details/8538592 (转)
- Web---JSP注册技术的的演绎(3代)-JSP/EJB/Servlet/POJO/JavaBean
我们可以这么理解JSP注册技术的发展过程: 第一代JSP技术:纯JSP开发. 第二代JSP技术:JSP+EJB开发. (EJB简单来说就是把已经编写好的程序(即:类)打包放在服务器上执行.) 第三代J ...
- bat 批处理 字符串 截取
由于项目中配置项太多,经常有同事在配置xml的时候,讲 配置的路径搞错,先需要搞一个脚本,可以自动将路径截取出来, 晚上收集了点资料,暂时先上几个 bat 后面留着 ,具体实现. @echo off ...
- vijosP1223麦森数
vijosP1223麦森数 链接:https://vijos.org/p/1223 [思路] 快速幂+高精乘. 计算2^p-1可以快速幂的方法在O(logn)的时间内出解,限于数据范围我们需要用到高精 ...
- 如何使用C#和VB发送和接收MSMQ消息
在这篇博客中,我们将就如何实现System.Messaging类发送和接收的XML消息发送从MSMQ队列,你可能会遇到接收的XML消息的一些问题. 我们将首先加入参考System.Messaging ...
- 集成电路中的assert和deassert应该如何翻译?
转载自:http://m.blog.csdn.net/blog/code_robot/37663085 我每次看到电路中的assert与deassert时,总是感觉别扭,因为词典翻译总是"断 ...
- 《Genesis-3D开源游戏引擎--横版格斗游戏制作教程06:技能播放的逻辑关系》
6.技能播放的逻辑关系 技能播放概述: 当完成对技能输入与检测之后,程序就该对输入在缓存器中的按键操作与程序读取的技能表信息进行匹配,根据匹配结果播放相应的连招技能. 技能播放原理: 按键缓存器中内容 ...
- POJ2299: Ultra-QuickSort-合并排序解决逆序数问题
#include<iostream> #include<malloc.h> using namespace std; long long ans; void merge(int ...
- POJ3356 – AGTC(区间DP&&编辑距离)
题目大意 给定字符串X和Y,可以对字符串进行一下三种操作: 1.删除一个字符 2.插入一个字符 3.替换一个字符 每个操作代价是1,问运用以上三种操作把X变为Y所需的最小步数是多少? 题解 定义dp[ ...