search
HomeBackend DevelopmentPHP TutorialMagento commonly used functions, magento commonly used functions_PHP tutorial

magento 常用的函数,magento常用函数

1.Magento eav_attribute表中source如何指定自定义数据来源
  如果你引用的类名为yebihai_usermanage_model_entity_school你必须完整的给出地址,不能usermanage/entity_school,这样默认是在Mage下面去找的。
  如:

$setup->addAttribute('customer', 'school', array( 'type' => 'int', 'input' => 'select', 'label' => 'School', 'global' => 1, 'visible' => 1, 'required' => 0, 'user_defined' => 1, 'default' => '0', 'visible_on_front' => 1, 'source'=> 'yebihai_usermanage_model_entity_school', //数据来源,text留空即可 ));


2.Magento getPrice()的结果小数点位数的处理
echo Mage::helper('core')->currency($_product->getPrice()); 
输出格式:888.673 => 888.67

3.Magento config.xml中global节点中的block重写与blocks下面的命名标签必须小写,如:


                                                Yebihai_CategoryList_Block_Category_View                                                                              Yebihai_CategoryList_Block                            


4.Magento获取列表当前排序方式ASC or DESC?
获取当前排序:$this->getAvailableOrders()
获取当前分页:$this->getCurrentPage()
列表页的各种内容获取都在:Mage_Catalog_Block_Product_List_Toolbar这个类里面,有需要直接去这里面找。

5.Magento Collection添加排序?

$subCategories = Mage::getModel('catalog/category')->getCollection(); $subCategories->setOrder('position', 'ASC');


6.Magento Collection where里面的或条件如何实现?

$result = $selfread->select()->from( $table, array('id'))  ->where( 'reid = '.$reid,'topid ='.$reid);//reid=$reid 或 topid=$reid


7.Magento操作某条数据下面的多个字段,使用场景如下:
本 人在做订单备注的时候在监听类里面通过Magento系统的addStatusHistoryComment方法把订单内容能成功写入 sales_flat_order_status_history表,但是我的需求是还要修改is_visible_on_front此字段的值,让内容 在前台可见。头痛的问题来了,想了各种方法最后按下面的方式解决了。
监听类全部源码:

class Yebihai_CustomerOrderComments_Model_Observer   { public function setCustomerOrderComments(Varien_Event_Observer $observer) { $_order = $observer->getEvent()->getOrder(); $_request = Mage::app()->getRequest(); $_comments = strip_tags($_request->getParam('customerOrderComments')); if(!empty($_comments)){ $_order->setCustomerNote('
订单备注: ' .$_comments); $_order->addStatusHistoryComment('订单备注: ' .$_comments)->setIsVisibleOnFront(1); } return $this; } }

8.Magento个人中心左侧菜单控制
关于个人中心的主要功能都是在customer这个模块进行,需要修改相应的功能,直接去你的模板customer文件夹去修改。
左侧菜单模板路径:customer/account/navigation.phtml
9.Magento把html转换为转义字符,用什么方法?
core助手里面有一个escapeHtml方法,使用如下:
Mage::helper('core')->escapeHtml("yebihai 加油

go
");
The actual location of the method: in the Mage_Core_Helper_Abstract class.
ps: Some common operation methods are encapsulated in the core module. If necessary, you can analyze the source code.

10.Magento dynamically creates blocks and references actions?

The following is the layout (Layout) configuration file of one of my modules. I now need to dynamically call checkoutcart through Ajax. Direct calling is definitely not possible. How to solve it? Yes?           simplecheckout/cart_item_renderer                            
Step 1: Call a custom controller through ajax, such as:
jQuery.post('getUrl('gouwuche/cart/updateQuickShoppingCar') ?>', function(data){ jQuery('#shopping-cart-table thead').after(data); }); Step 2: Dynamically create a block in the controller method, such as: public function updateQuickShoppingCarAction(){ $block = $this->getLayout()->createBlock('checkoutrewrite/quickcart')->setTemplate('quickbuy/cart/cart.phtml'); echo $block->toHtml(); }
Step 3: Create a new block file (quickcart), and initialize the action content in the configuration file in the construct method in this file, such as:
public function __construct() { parent::__construct(); $this->addItemRender('simple', 'checkout/cart_item_renderer', 'quickbuy/cart/item/item_view.phtml'); }

PS: When proceeding to the second step, the cart.phtml template has been loaded. The third step is just to load the action under the cart block.

11. What should we pay attention to in the parameters of Magento getTable method?
Instance, the method of querying the specified table and conditions in the database is as follows:

public function getExcelKucunJiage($id,$status){ $selfread = $this->_getConnection('excelmanage_read'); $table = $this->getTable('excelmanage/excelkucunjiage'); $result = $selfread->select() ->from( $table ) ->where( 'excel_id=?', $id) ->where( 'is_active=?', $status); return $selfread->fetchRow($result); }

The parameter settings of the getTable method need to be noted as follows. excelmanage is the name of your module, and excelkukunjiage is the name of the entity node you operate. My entity configuration is as follows:

Yebihai_ExcelManage_Model_Resource_Mysql4 excelkucunjiage

The parameters after "/" are derived from the entity names in front of the table.

12. How to update the specified ID information in the data table?
$excelModel = Mage::getModel('excelmanage/excelkukunjiage')->load(1);
$excelModel->setExcelAdddate(Mage::getModel('core/date')- >timestamp(time()));
$excelModel->setIsActive(0);
$excelModel->save();
The above code is to modify the data table information with ID 1 .
Extension: How to add and modify specified table information in Magento?

13. How to change the default sorting field of product list?
Set the path at: System-->Directory-->Advanced Product Management-->Default List Status

14. Get the number of items in a data set?

Get the number of _productCollection data sets, the case is as follows:

$this->setStoreId($storeId);

 $this->_productCollection = Mage::getResourceModel('catalog/product_collection'); //Get the data set

$this->_productCollection = $this->_productCollection->addAttributeToSelect('*')

->addAttributeToSelect('manufacturer') //Add query attribute

->setStoreId($storeId) //Set the store

 ->addAttributeToFilter('cuxiaobiaoqian',array('eq'=>39)) //Attribute filtering specification

->addStoreFilter($storeId) //Add store filter conditions

 ->setPageSize(6); //Get the number of items

15. Query the specified data table through the select() method. How to control the number of items read?

The code application background is as follows:

 $selfread = $this->_getConnection('yafo_bbs_setup'); //Database connection object

$table = $this->zixunTablePrefix."forum_post"; //Table to be queried

 $result = $selfread->select()->from( array('a'=>$table), array('tid','subject')) //Specify the table and the object to be queried Field

 ->limit($size) //Read the specified number of items

->order("a.dateline DESC") //Specify sorting conditions

 ->where( $selfwhere ); //Add filter conditions

Return $selfread->fetchAll($result); //Return query results

16. Modify the specified product price and group price (code operation)?

$selfPrc = Mage::getModel('catalog/product')->load(614); $selfData = $selfPrc->getData(); $selfData['price'] = 25; $selfData['group_price'] = array( 0 => Array(                                                        "website_id" => 0,                            "all_groups" => 0,                            "cust_group" => 0,                            "price" => 97.0000,                            "website_price" => 97.0000                        ),                      1=> Array                        (                            "website_id" => 0,                            "all_groups" => 0,                            "cust_group" => 1,                            "price" => 27.0000,                            "website_price" => 27.0000                        ),                      2=> Array                        (                            "website_id" => 0,                            "all_groups" => 0,                            "cust_group" => 2,                            "price" => 17.0000,                            "website_price" => 17.0000                        ),                      3=> Array                        (                           "website_id" => 0,                            "all_groups" => 0,                            "cust_group" => 3,                            "price" => 67.0000,                            "website_price" => 67.0000                        ),                      4=> Array                        (                            "website_id" => 0,                            "all_groups" => 0,                            "cust_group" => 4,                            "price" => 66.0000,                            "website_price" => 66.0000                        )); $selfPrc->setData($selfData); $selfPrc->save();


17.修改指定产品库存(代码操作)?

$selfPrc = Mage::getModel('catalog/product')->load(614); $aa = Mage::getModel("cataloginventory/stock_item")->loadByProduct($selfPrc); $selfaa = $aa->getData(); $selfaa['qty'] = 23; $aa->setData($selfaa); $aa->save();


18. How to output sql statement
$result = $selfread->select()->from(array('ft'=>$flatTable),array ())

->join(array('pc'=>$prcCategory),'ft.entity_id=pc.entity_id',array('pc.value')) ->where( 'ft.attribute_set_id=?', $attsetid) ->where( 'pc.attribute_id=?', $attid) ->group("pc.value"); //echo $result; exit;//Output sql statement


19. Background form configuration, how to add comments in the code?

$fieldset->addField('dict_grade', 'select', array( 'name' => 'dict_grade', 'label' => Mage::helper('catalogsearchrewrite')->__('Advanced Search Ciku Manage Grade'), 'title' => Mage::helper('catalogsearchrewrite')->__('Advanced Search Ciku Manage Grade'), 'type' => 'options', 'options' => Mage::getSingleton('catalogsearchrewrite/cikumanage')->getCikuGradeOptionArray(), 'after_element_html' => Mage::helper('catalogsearchrewrite')->__('Keywords Grade Description.'), //after_element_htmlThis attribute is used to add comments 'required' => true, ) );


20. Instantiate the model and how to get the value of the specified content of the specified field through the load method?
$dictModel=Mage::getModel('catalogsearchrewrite/cikumanage')->load($dictname,'dict_name'); //Parameter 1: Specify the value, Parameter 2: Specify the field

$dictModel->getDictName(); //Get the returned specified field value

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1135808.htmlTechArticlemagento commonly used functions, magento common functions 1. How to specify a custom data source in the source in the Magento eav_attribute table if you quote The class name is yebihai_usermanage_model_entity_school you...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.