Magento 模塊開發中高頻復用的核心代碼模式,涵蓋 EAV 屬性、價格格式化、Block 重寫、集合操作、觀察者、佈局動態渲染、數據庫資源模型、後台表單、SKU/庫存編程等 20 大場景,供開發者快速檢索復制。
完整類名必須包含命名空間前綴,不能用簡寫:
$setup->addAttribute('customer', 'school', [
'type' => 'int',
'input' => 'select',
'label' => 'School',
'source' => 'Vendor\Module\Model\Entity\School', // 完整類名
]);
echo $this->helper('Magento\Framework\Pricing\Helper\Data')
->currency($product->getPrice(), true, false);
關鍵規則:<blocks> 下所有節點名稱必須小寫:
<global>
<blocks>
<catalog>
<rewrite>
<category_view>Vendor\Module\Block\Category\View</category_view>
</rewrite>
</catalog>
<!-- 自定義 block 組名也必須小寫 -->
<vendor_module>
<class>Vendor\Module\Block</class>
</vendor_module>
</blocks>
</global>
$toolbar = $block->getToolbarBlock(); // Mage_Catalog_Block_Product_List_Toolbar
$currentOrder = $toolbar->getCurrentOrder(); // 'position'/'price'...
$currentDir = $toolbar->getCurrentDirection(); // 'asc'/'desc'
$currentPage = $toolbar->getCurrentPage();
$collection = $this->_categoryFactory->create()->getCollection();
$collection->setOrder('position', 'ASC');
$select = $connection->select()->from($table, 'id')
->where('reid = ? OR topid = ?', [$reid, $reid]);
class OrderCommentObserver implements ObserverInterface {
public function execute(EventObserver $observer) {
$order = $observer->getEvent()->getOrder();
$comment = $this->request->getParam('customerOrderComments');
if ($comment) {
$order->setCustomerNote('<br/><strong>備注:</strong> ' . $comment);
$order->addStatusHistoryComment('備注:' . $comment)
->setIsVisibleOnFront(true)
->save();
}
}
}
Magento_Customer::account/navigation.phtml
echo $this->helper('Magento\Framework\Escaper')
->escapeHtml("<b>test</b>");
Controller:
$block = $this->_view->getLayout()
->createBlock('Vendor\Module\Block\QuickCart')
->setTemplate('Vendor_Module::cart/cart.phtml');
echo $block->toHtml();
Block 構造函數中初始化 Action:
public function __construct(
Template\Context $context,
array $data = []
) {
parent::__construct($context, $data);
$this->addItemRender('simple', 'Magento\Checkout\Block\Cart\Item\Renderer', 'Vendor_Module::cart/item/view.phtml');
}
$table = $this->getTable('vendor_module/entity_name');
對應 etc/db_schema.xml 或舊版 config.xml 中 <entity_name><table>actual_table</table></entity_name>。
$model = $this->_modelFactory->create()->load($id);
$model->setData('field_name', $value)->save();
路徑:Stores → Configuration → Catalog → Catalog → Storefront → Default Product Listing Sort By
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*')
->addAttributeToFilter('promo_tag', 39)
->setPageSize(6);
$totalCount = $collection->getSize(); // 負載所有頁總數
$pageCount = $collection->getLastPageNumber();
$select = $connection->select()
->from(['a' => $table], ['tid', 'subject'])
->limit($size)
->order('a.dateline DESC')
->where($whereCondition);
return $connection->fetchAll($select);
$product = $this->_productRepository->getById(614);
$product->setPrice(25);
$product->setGroupPrice([
['website_id' => 0, 'cust_group' => 0, 'price' => 97],
['website_id' => 0, 'cust_group' => 1, 'price' => 27],
// ...
]);
$this->_productRepository->save($product);
$stockItem = $this->_stockRegistry->getStockItemBySku($product->getSku());
$stockItem->setQty(23)->setIsInStock(true);
$this->_stockRegistry->updateStockItemBySku($product->getSku(), $stockItem);
$select = $connection->select()->from(...);
// 方法一
echo $select->__toString();
// 方法二(推薦)
$this->_logger->debug((string)$select);
$fieldset->addField('grade', 'select', [
'label' => __('Grade'),
'after_element_html' => __('Grade description help text.'),
'required' => true,
]);
$model = $this->_modelFactory->create()->load($value, 'field_name');
$fieldValue = $model->getData('field_name');
提示:Magento 2 建議使用 Service Contracts(Repository/Interface)替代直接調用 Model/Collection,上述代碼為兼容性展示,實際項目請優先注入對應 Repository Interface。