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的一些小技巧(转)的更多相关文章
- 前端网络、JavaScript优化以及开发小技巧
一.网络优化 YSlow有23条规则,中文可以参考这里.这几十条规则最主要是在做消除或减少不必要的网络延迟,将需要传输的数据压缩至最少. 1)合并压缩CSS.JavaScript.图片,静态资源CDN ...
- Git小技巧 - 指令别名及使用Beyond Compare作为差异比较工具
前言 本文主要写给使用命令行来操作Git的用户,用于提高Git使用的效率.至于使用命令还是GUI(Tortoise Git或VS的Git插件)就不在此讨论了,大家根据自己的的喜好选择就好.我个人是比较 ...
- 分享两个BPM配置小技巧
1.小技巧 流程图修改后发布的话版本号会+1,修改次数多了之后可能会导致版本号很高,这个时候可以将流程导出,然后删除对应的流程包再导入,发布数据模型和流程图之后,版本清零 2.小技巧 有的同事入职后使 ...
- linux系统维护时的一些小技巧,包括系统挂载新磁盘的方法!可收藏!
这里发布一些平时所用到的小技巧,不多,不过会持续更新.... 1.需要将history创建硬链接ln 全盘需要备份硬链接 ln /etc/xxx /home/xxx 2.root用户不可以远程 /et ...
- JS处理事件小技巧
今天,就分享一下我自己总结的一些JS的小技巧: ①防止鼠标选中事件 <div class="mask" onselectstart="return false&qu ...
- iOS:小技巧(不断更新)
记录下一些不常用技巧,以防忘记,复制用. 1.获取当前的View在Window的frame: UIWindow * window=[[[UIApplication sharedApplication] ...
- css小技巧(1)
1.-webkit-overflow-scrolling: touch; 解决ios滑动时无缓冲问题 2.::-webkit-scrollbar 设置ios滑动时是否显示滚动条 3.::selecti ...
- 最强 Android Studio 使用小技巧和快捷键
写在前面 本文翻译自 Android Studio Tips by Philippe Breault,一共收集了62个 Android Studio 使用小技巧和快捷键. 根据这些小技巧的使用场景,本 ...
- ios开发中的小技巧
在这里总结一些iOS开发中的小技巧,能大大方便我们的开发,持续更新. UITableView的Group样式下顶部空白处理 //分组列表头部空白处理 UIView *view = [[UIViewal ...
随机推荐
- 准确率,召回率,F值,机器学习分类问题的评价指标
下面简单列举几种常用的推荐系统评测指标: 1.准确率与召回率(Precision & Recall) 准确率和召回率是广泛用于信息检索和统计学分类领域的两个度量值,用来评价结果的质量.其中精度 ...
- 设置py文件的路径
想在IDLE中打开py文件,需要设置PYTHONPATH环境变量: 设置后,就能在IDLE的Path Browser中看到sys.path了: 然后,就可以用import了
- 如何用Docker建立一个Node.js的开发环境
建立一个文件夹 用管理员身份打开powershell. 在文件夹下面运行npm init, 根据提示填入信息,以便产生一个package.json文件. 在文件中加入需要的dependencies ...
- [Docker] Converting from Docker Compose to Kubernetes
kompose is a tool to help users who are familiar with docker-compose move to Kubernetes. kompose tak ...
- maven 管理
http://www.cnblogs.com/qq78292959/p/3711501.html
- JavaScript Array 对象扩展方法
/** 删除数组中指定索引的数据 **/ Array.prototype.deleteAt = function (index) { if (index < 0) { return this; ...
- Read from socket failed: Connection reset by peer.
复制密钥另一台主机时,出现了错误: Read from socket failed: Connection reset by peer. 到被登录主机的/var/log/auth.log查看日志: M ...
- notepad++一键运行python
打开notepad++,找到菜单栏的run菜单. 子菜单选中run 弹出的小窗口中,输入cmd /k python "$(FULL_CURRENT_PATH)" & ...
- 理解CPU steal time
http://melody-dc.com/2015/11/21/%E7%90%86%E8%A7%A3CPU-steal-time/ http://www.cnblogs.com/yjf512/p/33 ...
- mysql如何分类统计数量
比如我表test里面有id,mc,xh三个字段(分别是自动编号,钢材名称(若干种),钢材型号(大号,中号,小号)) id mc xh 钢管 大号 铜管 大号 铁管 小号 铝管 中号 钢管 小号 我现在 ...