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'); orMage::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 config16. 获取当前的时间$date = Mage::app()->getLocale()->date(Mage::getSingleton('core/date')->gmtTimestamp(), null, null);$date = $date->toString('yyyy-MM-dd hh:m:s');17. generate skin urlMage::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 221. 发送邮件 $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 firefox6so just remove or comment the id "#loading-mas" about <!-- opacity: 0.8;-->,it will solve it29. get attributeSetId by attributeNameMage::getResourceModel('eav/entity_attribute_set_collection') ->addFieldToFilter('attribute_set_name',$attributSetName) ->getFirstItem()->getId();30. get attributeSetName by attributeSetIdMage::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 viewif( 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. 常用的loadMage::getModel('sales/order')->load();
Mage::getModel('customer/customer')->load();Mage::getModel('catalog/product')->load();