关于magento2:Display-formkey-in-knockoutjs-template

This is how the core achieves this: Javascript file: vendor/magento/module-checkout/view/frontend/web/js/view/payment.js:98getFormKey: function () { return window.checkoutConfig.formKey;}HTML file: vendor/magento/module-checkout/view/frontend/web/template/payment.html:19<form id="co-payment-form" class="form payments" novalidate="novalidate"> <input data-bind='attr: {value: getFormKey()}' type="hidden" name="form_key"/> ...</form>

March 4, 2024 · 1 min · jiezi

关于magento2:Adding-custom-global-javascript-validation

Assuming you add a validation class via the frontend_class let's say "validate-custom-class" you'll need to use the following JS to add a custom validation based on a this class: require([ 'jquery', 'jquery/ui', 'jquery/validate', 'mage/translate'], function($){ $.validator.addMethod( 'validate-custom-class', function (value) { // Add your validation logic here // Needs to return true if validation pass // Or false if validation fails }, $.mage.__('Field is not valid'));});

March 4, 2024 · 1 min · jiezi

关于magento2:EventObserver-for-whenever-the-stock-status-of-product-changes

You can use catalog_product_save_after, checkout_submit_all_after ,cataloginventory_stock_revert_products_sale, sales_order_item_cancel(Depending ) and get the stock status. You can even check for that product attribute value is as desired out of stock and that out of stock do nothing else update the attribute value .Put this events.xml in below path app\code\YOUR_NAMESPACE\YOURMODULE\etc\ <?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="catalog_product_save_after"> <observer name="test_name" instance="YOUR_NAMESPACE\YOUR_MODULENAME\Observer\Productsaveafter" /> </event></config>And put your Productsaveafter.php in below path app\code\YOUR_NAMESPACE\YOURMODULE\Observer\ <?phpnamespace YOURNAMESPACE\YOURMODULENAME\Observer;use Magento\Framework\Event\ObserverInterface;class Productsaveafter implements ObserverInterface{ public function execute(\Magento\Framework\Event\Observer $observer) { $_product = $observer->getProduct(); // you will get product object and you can check for stock and attribute values here } }

April 19, 2023 · 1 min · jiezi

关于magento2:Load-additional-product-attributes-in-Wishlist

Where are the products loaded?The products are loaded in the "_afterLoad" method of the items collection. A product collection is instantiated there based on the product ids of all items and directly loaded to assign the products to their wishlist items. Unfortunately it is instantiated and loaded from within the same method, so it is not easily changed via plugin. The attributes to select are hard coded: $attributesToSelect = [ 'name', 'visibility', 'small_image', 'thumbnail', 'links_purchased_separately', 'links_title', ];The method dispatches an event wishlist_item_collection_products_after_load, but unfortunately no "before load" event. ...

February 22, 2023 · 2 min · jiezi

关于magento2:How-to-add-tooltip-in-Magento-2

I am using a custom template and just added: <span class="custom-tooltip"> <a href="#" class="tooltip-toggle">Test ?</a> <span class="tooltip-content">Tolltip description come here</span></span>and than added below style code in my theme styles-l.css .custom-tooltip { .lib-tooltip(right);}and run command belowbin/magento setup:upgrade

February 17, 2023 · 1 min · jiezi

关于magento2:remove-reivew

<referenceBlock name="reviews.tab" remove="true" /> <referenceBlock name="product.review.form" remove="true" /> <referenceBlock name="product.info.review" remove="true" />

February 8, 2023 · 1 min · jiezi

关于magento2:get-child-item-id-of-configurable-product-by-super-attribute

Let’s assume you know configurable product id and used child product super attribute details.Example from Magento Sample data configurable product name Chaz Kangeroo Hoodie, Configurable product id is 67.Super attribute Array details, [super_attribute] => Array( [93] => 49 [254] => 167)Using the bove details how we can get details of child item. Refer below code snippet for Get child item id of a Configurable product by child’s Attribute details. ...

February 3, 2023 · 1 min · jiezi

关于magento2:Magento-2-允许内存耗尽错误

在本文中,咱们将理解问题的起因以及如何解决 Magento2 中“容许的内存耗尽谬误”的问题。 “allowed memory size of bytes exhausted”谬误的起因与内存不足无关。如果您尝试应用比您通过“memory_limit”在 php.ini 文件中指定的更多的 RAM 资源,则会产生谬误。 解决方案1: 在 php.ini 文件中,搜寻并更改以下值,如下所示 max_execution_time=18000 max_input_time=1800 memory_limit=4G并重新启动 Apache。解决方案2: Magento 2 命令中内存限度的疾速解决方案是间接在命令中增加内存限度。对于编译命令, php -dmemory_limit=4G bin/magento setup:di:compile用于部署 php -dmemory_limit=4G bin/magento setup:static-content:deploy如果问题没有解决,您能够依据 4G 更改为最大。 解决方案3: - 您能够应用此命令而不是 bin/magento 轻松修复它: php -dmemory_limit=-1 bin/magento ....例子: php -dmemory_limit=-1 bin/magento 设置:降级php -dmemory_limit=-1 bin/magento setup:di:compile此谬误与 PHP 中的内存限度配置无关。参数 -dmemory_limit=-1容许在没有内存限度的命令行中运行 PHP。 心愿这些解决方案能够帮忙您解决问题。

December 15, 2022 · 1 min · jiezi

关于magento2:check-if-a-product-is-already-on-the-wishlist-in-Magento2

亲测无效 <?php //Checking User logedin or not $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $context = $objectManager->get('Magento\Framework\App\Http\Context'); $isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH); $customerSession = $objectManager->create("Magento\Customer\Model\Session"); if($customerSession->isLoggedIn()){ //getting customer ID $id = $customerSession->getCustomerID(); } //Getting wishlist products Collections Related to Customers $wishlist = $objectManager->get('\Magento\Wishlist\Model\Wishlist'); $wishlist_collection = $wishlist->loadByCustomerId( $id , true)->getItemCollection(); $_in_wishlist = "false"; foreach ($wishlist_collection as $wishlist_product): if($_product->getId() == $wishlist_product->getProduct()->getId()){ $_in_wishlist = "true"; break; } endforeach; if($_in_wishlist == "true"): ?> <div class="addtowishlist added" style="font-family: Raleway"><span>Already Added to Wishlist:</span><div data-role="add-to-links" class="actions-secondary"<?= strpos($pos, $viewMode . '-secondary') ? $position : '' ?>> <?php if ($addToBlock = $block->getChildBlock('addto')): ?> <?= $addToBlock->setProduct($_product)->getChildHtml() ?> <?php endif; ?> </div> </div> <?php else: ?> <div class="addtowishlist" style="font-family: Raleway"><span>Add to Wishlist:</span><div data-role="add-to-links" class="actions-secondary"<?= strpos($pos, $viewMode . '-secondary') ? $position : '' ?>> <?php if ($addToBlock = $block->getChildBlock('addto')): ?> <?= $addToBlock->setProduct($_product)->getChildHtml() ?> <?php endif; ?> </div> </div> <?php endif; ?>

November 30, 2022 · 1 min · jiezi

关于magento2:PluginListGeneratorphp-in-Magento-242-during-compilation

To fix above error, kindly follow the below steps Open PluginListGenerator.php file located at vendor/magento/framework/Interception. Go to line no 414 or find the word “scopePriorityScheme” in PluginListGenerator.php file. Replace the line "$cacheId = implode('|', $this->scopePriorityScheme) . "|" . $this->cacheId;" with"$cacheId = implode('-', $this->scopePriorityScheme) . "-" . $this->cacheId;"

November 21, 2022 · 1 min · jiezi

关于magento2:php版本错误导致的报错

因为我有2个magento我的项目,一个版本是2.3.2,一个是2.4.2,以后PHP版本是7.3,当我运行任何命令都会呈现一下谬误: PDOException: SQLSTATE[HY000] [2002] Connection refused in /var/www/html/vendor/magento/zendframework1/library/Zend/Db/Adapter/Pdo/Abstract.php:128 Stack trac查找材料发现是PHP版本导致的报错,于是我升高PHP版本为7.2,就没有这个报错了

July 12, 2022 · 1 min · jiezi

关于magento2:continue-targeting-switch-is-equivalent-to-break

本地环境呈现谬误 Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? 解决办法:composer install

July 7, 2022 · 1 min · jiezi

关于magento2:如何安装-Magento-2-安全补丁

https://www.mageplaza.com/kb/...

May 13, 2022 · 1 min · jiezi

关于magento2:通过option-id拿到对应的option-label值

We can get hash code value of specific visual swatch by swatch option id.We have created Color Product attribute from Stores -> Attributes -> Product.Color attribute code with Catalog Input Type for Store Owner set to Visual swatch. Now We can get the color hash code by color option id using below code snippet. public function __construct( \Magento\Swatches\Helper\Data $swatchHelper,) { $this->swatchHelper = $swatchHelper;}/* Get Hashcode of Visual swatch by option id */public function getAtributeSwatchHashcode($optionid) { $hashcodeData = $this->swatchHelper->getSwatchesByOptionsId([$optionid]); return $hashcodeData[$optionid]['value'];}Call getAtributeSwatchHashcode() function from template, ...

May 11, 2022 · 1 min · jiezi

关于magento2:怎么拿到Configurable类型产品的子产品的属性值

You can retrieve the Children item used super attribute label value data from the child and parent product SKU of the configurable product. This article is useful when you are programmatically adding a Configurable product to the cart. Let’s take an example, You need to fetch used super attribute value of the child item, native Magento sample data configurable product name, Cassius Sparring Tank has product SKU MT12 and its child product name Cassius Sparring Tank-XL-Blue has product SKU MT12-XL-Blue. ...

May 11, 2022 · 2 min · jiezi

关于magento2:怎么在magento中执行命令

我的项目中有需要须要执行完指定代码进行从新索引和刷新缓存,Google找了一堆文章,最多的就是这个,我就用 $command = ' php bin/magento indexer:reindex'; shell_exec($command);后果提醒谬误Could not open input file: bin/magento查了一下这个是因为目录不对,而后我就在这个根底上改良了如下就解决了 $command = 'cd '.$this->rootPath.' && php bin/magento indexer:reindex'; shell_exec($command);

May 7, 2022 · 1 min · jiezi

关于magento2:Fatal-error-require-Failed-opening-required

当手动删除通过composer装置的插件时呈现谬误 Fatal error: require(): Failed opening required '/www/wwwroot/th-test/vendor/composer/../rltsquare/best-seller/registration.php' (include_path='/www/wwwroot/th-test/vendor/magento/zendframework1/library:.:/www/server/php/73/lib/php') in /www/wwwroot/th-test/vendor/composer/autoload_real.php on line 75只须要通过上面命令就能够解决composer dump-autoload

March 9, 2022 · 1 min · jiezi

关于magento2:Error-viewing-sales-transactions-in-admin-Magento-2

当我新增一个领取形式时,查看后盾订单呈现以下谬误: Exception # 0 (Exception): Notice: Undefined index: label in /vendor/magento/module-backend/Block/Widget/Grid/Column/Filter/Select.php on line 75 查看后发现是/etc/config.xml中group的大小写问题

January 17, 2022 · 1 min · jiezi

关于magento2:Syntax-error-or-access-violation-1103-Incorrect-table-name

Above error occurs when there is missing tables for multi-stores. The main reason behind the issue is when the migration is done using any third party extension not done by Data migration tool. NOTE: Please take backup of database before applying any changes! You will notice that, following tables may be Missing: Assumption: store 1, store 2 are working fine, if store 3 is not functioning properly. If store 3 is not working properly then these tables need to be created: ...

December 8, 2021 · 2 min · jiezi

关于magento2:Cant-display-frontend-in-iframe

November 19, 2021 · 0 min · jiezi

关于magento2:Solved-Class-ZendSerializerSerializer-not-found

Magento 2.4.3 version has been released on 10th August 2021, for both Commerce/Cloud and Open Source editions. After upgrading to Magento 2.4.3 you may have Class "Zend\Serializer\Serializer" not found or "Zend\Serializer\Adapter\PhpSerialize" not found errors on some of your third party extensions that use "Zend\Serializer\Serializer" or "Zend\Serializer\Adapter\PhpSerialize" classes. What Is The Cause?The cause is that "laminas/laminas-serializer" package is missing in Magento 2.4.3 composer.json by default. This package along with other laminas packages that were on Magento 2.4.2 has been removed in Magento 2.4.3 composer.json. ...

November 9, 2021 · 2 min · jiezi

关于magento2:安装sample-data

1.Install sample data modules php bin/magento sampledata:deploy2.Enable sample data modules (it's important!): php bin/magento module:enable Magento_CustomerSampleData Magento_MsrpSampleData Magento_CatalogSampleData Magento_DownloadableSampleData Magento_OfflineShippingSampleData Magento_BundleSampleData Magento_ConfigurableSampleData Magento_ThemeSampleData Magento_ProductLinksSampleData Magento_ReviewSampleData Magento_CatalogRuleSampleData Magento_SwatchesSampleData Magento_GroupedProductSampleData Magento_TaxSampleData Magento_CmsSampleData Magento_SalesRuleSampleData Magento_SalesSampleData Magento_WidgetSampleData Magento_WishlistSampleData3.Remove old files: rm -rf var/cache/* var/page_cache/* var/generation/*4.Upgrade magento files:bin/magento setup:upgrade 5.Recompile files:bin/magento setup:di:compile 6.Do reindex:bin/magento indexer:reindex 7.Deploy static content:bin/magento setup:static-content:deploy

October 13, 2021 · 1 min · jiezi

关于magento2:SQLSTATEHY000-General-error-1419

报错:magento2SQLSTATE[HY000]: General error: 1419 You do not have the SUPER privilege and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable), query was: DROP TRIGGER IF EXISTS trg_catalog_category_entity_after_insert 解决办法: set global log_bin_trust_function_creators=1;

October 8, 2021 · 1 min · jiezi

关于magento2:Adding-additional-variables-in-windowcheckoutConfig

We often need to add more variables that we need to use on the checkout page at the time of checkout. Here is how we can do that. The first step is to add the following code in Vendor/Module/etc/frontend/di.xml of your custom module – <?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Checkout\Model\CompositeConfigProvider"> <arguments> <argument name="configProviders" xsi:type="array"> <item name="additional_provider" xsi:type="object">Webkul\Test\Model\AdditionalConfigVars</item> </argument> </arguments> </type></config>After this, we will create AdditionalConfigVars.php in Vendor/Module/Model and add the following code to it – ...

September 26, 2021 · 1 min · jiezi

关于magento2:编译出现-PluginListGeneratorphp错误

问题:最近在装置一个新的插件,编译发现如下谬误: 解决办法:关上文件 vendor/magento/framework/Interception/PluginListGenerator.php更新 $cacheId = implode('|', $this->scopePriorityScheme) . "|" . $this->cacheId;为 $cacheId = implode('-', $this->scopePriorityScheme) . "-" . $this->cacheId;这样从新进行编译就能够了

September 24, 2021 · 1 min · jiezi

关于magento2:Magento-235-在ubuntu-2004-安装记录-LAMP

Magento 2.3.5 在ubuntu 20.04 装置记录 LAMP

September 12, 2021 · 1 min · jiezi

关于magento2:magento-2-create-categories-programmatically-duplicate

use \Magento\Framework\App\Bootstrap;include('../app/bootstrap.php');$bootstrap = Bootstrap::create(BP, $_SERVER);$objectManager = $bootstrap->getObjectManager();$url = \Magento\Framework\App\ObjectManager::getInstance();$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');$mediaurl= $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);$state = $objectManager->get('\Magento\Framework\App\State');$state->setAreaCode('frontend');/// Get Website ID$websiteId = $storeManager->getWebsite()->getWebsiteId();echo 'websiteId: '.$websiteId." ";/// Get Store ID$store = $storeManager->getStore();$storeId = $store->getStoreId();echo 'storeId: '.$storeId." ";/// Get Root Category ID$rootNodeId = $store->getRootCategoryId();echo 'rootNodeId: '.$rootNodeId." ";/// Get Root Category$rootCat = $objectManager->get('Magento\Catalog\Model\Category');$cat_info = $rootCat->load($rootNodeId);$categorys=array('Levis','Wranglers','Basics'); // Category Namesforeach($categorys as $cat){$name=ucfirst($cat);$url=strtolower($cat);$cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));$categoryFactory=$objectManager->get('\Magento\Catalog\Model\CategoryFactory');/// Add a new sub category under root category$categoryTmp = $categoryFactory->create();$categoryTmp->setName($name);$categoryTmp->setIsActive(true);$categoryTmp->setUrlKey($cleanurl);$categoryTmp->setData('description', 'description');$categoryTmp->setParentId($rootCat->getId());$mediaAttribute = array ('image', 'small_image', 'thumbnail');$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false);// Path pub/meida/catalog/category/m2.png$categoryTmp->setStoreId($storeId);$categoryTmp->setPath($rootCat->getPath());$categoryTmp->save();

August 19, 2021 · 1 min · jiezi

关于magento2:Missing-required-argument-engines-of-MagentoFrameworkView

Missing required argument $engines of Magento\Framework\View\TemplateEngineFactory

August 4, 2021 · 1 min · jiezi

Grunt运行报错

开发magento 2运行 grunt less:luma报错 grunt-cli: The grunt command line interface (v1.2.0)Fatal error: Unable to find local grunt.If you're seeing this message, grunt hasn't been installed locally toyour project. For more information about installing and configuring grunt,please see the Getting Started guide:http://gruntjs.com/getting-started这个错代表没有本地grunt,在项目目录执行: npm install grunt --save-dev

November 4, 2019 · 1 min · jiezi

Magento-2-新增表及Create-Model

New table by UpgradeSchemaRoute: code/Vender_name/Module_name/Setup/UpgradeSchema.php <?phpnamespace Vender_name\Module_name\Setup;use Magento\Framework\Setup\UpgradeSchemaInterface;use Magento\Framework\Setup\ModuleContextInterface;use Magento\Framework\Setup\SchemaSetupInterface;use Magento\Framework\DB\Ddl\Table;class UpgradeSchema implements UpgradeSchemaInterface{ /** * @param SchemaSetupInterface $setup * @param ModuleContextInterface $context */ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); if (version_compare($context->getVersion(), '1.0.1') < 0) { if ($setup->getConnection()->isTableExists($setup->getTable('supplier_data')) != true) { $table = $setup->getConnection() ->newTable($setup->getTable('supplier_data')) ->addColumn( 'supplier_id' , Table::TYPE_INTEGER , null , [ 'identity' => true , 'unsigned' => true , 'nullable' => false , 'primary' => true ] , 'Supplier Id' )->addColumn( 'supplier_name' , Table::TYPE_TEXT , 255 , ['nullable' => false , 'default' => ''] , 'Supplier Name' )->addColumn( 'mobile' , Table::TYPE_TEXT , 255 , ['nullable' => false , 'default' => ''] , 'Supplier Mobile' )->addColumn( 'address' , Table::TYPE_TEXT , 255 , ['nullable' => false , 'default' => ''] , 'Supplier Address' )->addColumn( 'city' , Table::TYPE_TEXT , 255 , ['nullable' => false , 'default' => ''] , 'Supplier City' )->addColumn( 'country' , Table::TYPE_TEXT , 255 , ['nullable' => false , 'default' => ''] , 'Supplier Country' )->addColumn( 'link' , Table::TYPE_TEXT , 255 , ['nullable' => false , 'default' => ''] , 'Supplier Link' )->addColumn( 'status' , Table::TYPE_SMALLINT, null , ['nullable' => false , 'default' => 0] , 'Status' )->addColumn( 'created_at' , Table::TYPE_TIMESTAMP , null , ['nullable' => false , 'default' => ''] , 'Created Date' )->addColumn( 'updated_at' , Table::TYPE_TIMESTAMP , null , ['nullable' => false , 'default' => ''] , 'Updated Date' ) ->setComment('Supplier Table') ->setOption('type', 'InnoDB') ->setOption('charset', 'utf8'); $setup->getConnection()->createTable($table); } } $setup->endSetup(); }}执行 php bin/magento setup:upgrade注:执行命令前检查module.xml文件中的版本是否更改 ...

May 24, 2019 · 2 min · jiezi

Magento-2-常用代码

Object/** * @param $className * @return mixed */public function getObject($className){ return \Magento\Framework\App\ObjectManager::getInstance()->get($className);}/** * @param $className * @return mixed */public function createObject($className){ return \Magento\Framework\App\ObjectManager::getInstance()->create($className);}Url/** * Generate url by route and parameters * * @param string $route * @param array $params * @return string */public function getUrl($route = '', $params = []){ return $this->urlManager->getUrl($route, $params);}/** * @return string */public function getRefer(){ return $this->urlEncoder->encode($this->urlManager->getCurrentUrl());}/** * @return string */public function decodeUrl($refer){ return $this->urlDecoder->decode($refer);}注:urlManager —> \Magento\Framework\UrlInterfaceurlEncoder -> \Magento\Framework\Url\EncoderInterfaceurlDecoder -> \Magento\Framework\Url\DecoderInterfaceProduct object$product = \Magento\Framework\App\ObjectManager::getInstance()->create('Magento\Catalog\Model\Product')->load($productId); // by id$product = \Magento\Framework\App\ObjectManager::getInstance()->create('Magento\Catalog\Api\ProductRepositoryInterface')->get($sku); // by skuProduct custom attribute and attribute label// attribute$product = \Magento\Framework\App\ObjectManager::getInstance()->create('Magento\Catalog\Model\Product')->load($productId);$attribute = $product->getData($attributeName);// attribute label$attributeLabel = $product->getAttributeText($attributeName);// or$attributeLabel = $product->getResource()->getAttribute($attributeName)->getFrontend()->getValue($product);Categories$objectManger = \Magento\Framework\App\ObjectManager::getInstance();$categoryHelper = $objectManger->create('Magento\Catalog\Helper\Category');$categories = $categoryHelper->getStoreCategories($sorted = false, $asCollection = false, $toLoad = true);$menus = array();foreach ($categories as $category){ $sub = array(); $sub['name'] = $category->getName(); $sub['link'] = $categoryHelper->getCategoryUrl($category); $menus[] = $sub;}Category custom attribute$objectManger = \Magento\Framework\App\ObjectManager::getInstance();$categoryModel = $objectManger->get('Magento\Catalog\Model\Category')->load($categoryId);$attribute = $categoryModel->getData('attribute_name');Logo and Copyright// Logo$objectManger = \Magento\Framework\App\ObjectManager::getInstance();$logoObject = $objectManger->create('Magento\Theme\Block\Html\Header\Logo');$logo = $logoObject->getLogoSrc();// Copyright$footer = $objectManger->create('Magento\Theme\Block\Html\Footer');$copyright = $footer->getCopyright();Format price$objectManager = \Magento\Framework\App\ObjectManager::getInstance();$priceHelper = $objectManager->create('Magento\Framework\Pricing\Helper\Data');$price = 998;$formattedPrice = $priceHelper->currency($price, true, false); // eg:EGP998.00注: 已convert价格$priceHelper = $objectManager->get('Magento\Framework\Pricing\PriceCurrencyInterface');$formatPrice = $priceHelper->format($price);注: 未convert价格Resize product image/** * Resize product image * * @param $imageFile * @param $size * @return mixed */public function resizeProductImage($imageFile, $size){ $imageObj = $objectManager->get("Magento\Catalog\Model\Product\Image"); $imageObj->setDestinationSubdir("image"); $imageObj->setSize($size); $imageObj->setBaseFile($imageFile); if (!$imageObj->isCached()) { $imageObj->resize(); $imageObj->saveFile(); } return $imageObj->getUrl();}Customer session/** * Return customer session model * * @return mixed */public function getCustomerSession(){ return \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Customer\Model\Session');}Get params$params = $this->_request->getParams();$param = $this->_request->getParam($key);用户验证$authentication = $objectManager->get("Magento\Customer\Model\Authentication");$customerId = $this->getCustomerSession()->getCustomer()->getId();$currentPassword = $this->_request->getParam('current_password');$checkResult = $authentication->authenticate($customerId, $currentPassword); // 返回值为 ture/false自定义前缀 (Custom prefix of order/invoice/shipment/creditmemo)UPDATE sales_sequence_profile SET prefix = 'order-' WHERE meta_id in (SELECT meta_id FROM sales_sequence_meta WHERE entity_type='order' AND store_id !=0);UPDATE sales_sequence_profile SET prefix = 'invoice-' WHERE meta_id in (SELECT meta_id FROM sales_sequence_meta WHERE entity_type='invoice' AND store_id !=0);UPDATE sales_sequence_profile SET prefix = 'shipment-' WHERE meta_id in (SELECT meta_id FROM sales_sequence_meta WHERE entity_type='shipment' AND store_id !=0);UPDATE sales_sequence_profile SET prefix = 'creditmemo-' WHERE meta_id in (SELECT meta_id FROM sales_sequence_meta WHERE entity_type='creditmemo' AND store_id !=0);

May 13, 2019 · 2 min · jiezi

Magento-2-新增用户字段Add-custom-column-to-customerentity

1、UpgradeSchema.php<?phpnamespace VenderName\ModuleName\Setup;use Magento\Framework\Setup\UpgradeSchemaInterface;use Magento\Framework\Setup\ModuleContextInterface;use Magento\Framework\Setup\SchemaSetupInterface;class UpgradeSchema implements UpgradeSchemaInterface{ /** * @param SchemaSetupInterface $setup * @param ModuleContextInterface $context */ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); if (version_compare($context->getVersion(), '1.0.1', '<')) { $setup->getConnection()->addColumn( $setup->getTable('customer_entity'), 'account_type', [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, 'nullable' => true, 'default' => null, 'comment' => 'Account type (0:old website account 1:new website account)' ] ); } $setup->endSetup(); }}2、UpgradeData.php<?phpnamespace VenderName\ModuleName\Setup;use Magento\Eav\Setup\EavSetupFactory;use Magento\Framework\Setup\UpgradeDataInterface;use Magento\Framework\Setup\ModuleContextInterface;use Magento\Framework\Setup\ModuleDataSetupInterface;/** * @codeCoverageIgnore */class UpgradeData implements UpgradeDataInterface{ /** * @var \Magento\Eav\Setup\EavSetupFactory */ protected $eavSetupFactory; /** * @var \Magento\Eav\Model\Config */ protected $eavConfig; /** * @param EavSetupFactory $eavSetupFactory * @param \Magento\Eav\Model\Config $eavConfig */ public function __construct( \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory, \Magento\Eav\Model\Config $eavConfig ) { $this->eavSetupFactory = $eavSetupFactory; $this->eavConfig = $eavConfig; } public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { if (version_compare($context->getVersion(), '1.0.1') < 0) { $setup->startSetup(); $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->addAttribute( \Magento\Customer\Model\Customer::ENTITY, 'account_type', [ 'type' => 'static', 'label' => 'Account Type', 'input' => 'select', 'source' => 'VenderName\ModuleName\Model\Config\Source\AccountType', 'required' => false, 'visible' => true, 'user_defined' => true, 'position' => 999, 'system' => false ] ); $attribute = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'account_type'); $attribute->setData( 'used_in_forms', ['adminhtml_customer', 'customer_account_create', 'customer_account_edit', 'checkout_register'] ); $attribute->save(); $setup->endSetup(); } }}3、AccountType.php<?phpnamespace VenderName\ModuleName\Model\Config\Source;class AccountType extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource{ /** * Get all options * * @return array */ public function getAllOptions() { if ($this->_options === null) { $this->_options = [ ['value' => '', 'label' => __('Please Select')], ['value' => '0', 'label' => __('Old Account')], ['value' => '1', 'label' => __('New Account')] ]; } return $this->_options; } /** * Get text of the option value * * @param string|integer $value * @return string|bool */ public function getOptionValue($value) { foreach ($this->getAllOptions() as $option) { if ($option['value'] == $value) { return $option['label']; } } return false; }}代码添加后,执行 php bin/magento setup:upgrade ,字段即添加成功。注:执行脚本之前最好确认下模块(module.xml)的版本号是否也已修改;后续对该字段的获取和设值可通过 Customer Model 来处理,示例如下: ...

May 13, 2019 · 2 min · jiezi

Magento-2-invoiceshipment-PDF中文乱码及内容过长未自动换行问题

PDF中文乱码1、添加支持的中文字体(SourceHanSans-Regular.ttf)    将字体放到 lib/internal/GnuFreeFont/ 目录下即可 2、重写\Magento\Sales\Model\Order\Pdf\Invoice及 Magento\Sales\Model\Order\Pdf\Shipment (注:抽象类 Magento\Sales\Model\Order\Pdf\AbstractPdf 不支持重写,所以需要重写继承了它的子类)    1)di.xml <?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <!--Pdf support chinese fonts--> <preference for="Magento\Sales\Model\Order\Pdf\Invoice" type="Vendor_name\Module_name\Model\Order\Pdf\Invoice" /> <preference for="Magento\Sales\Model\Order\Pdf\Shipment" type="Vendor_name\Module_name\Model\Order\Pdf\Shipment" /></config>    2)Vendor_name\Module_name\Model\Order\Pdf\Invoice.php <?phpnamespace Vendor_name\Module_name\Model\Order\Pdf;class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice{ /** * Set font as regular * * @param \Zend_Pdf_Page $object * @param int $size * @return \Zend_Pdf_Resource_Font */ protected function _setFontRegular($object, $size = 7) { $font = \Zend_Pdf_Font::fontWithPath( $this->_rootDirectory->getAbsolutePath('lib/internal/GnuFreeFont/SourceHanSans-Normal.ttf') ); $object->setFont($font, $size); return $font; } /** * Set font as bold * * @param \Zend_Pdf_Page $object * @param int $size * @return \Zend_Pdf_Resource_Font */ protected function _setFontBold($object, $size = 7) { $font = \Zend_Pdf_Font::fontWithPath( $this->_rootDirectory->getAbsolutePath('lib/internal/GnuFreeFont/SourceHanSans-Normal.ttf') ); $object->setFont($font, $size); return $font; } /** * Set font as italic * * @param \Zend_Pdf_Page $object * @param int $size * @return \Zend_Pdf_Resource_Font */ protected function _setFontItalic($object, $size = 7) { $font = \Zend_Pdf_Font::fontWithPath( $this->_rootDirectory->getAbsolutePath('lib/internal/GnuFreeFont/SourceHanSans-Normal.ttf') ); $object->setFont($font, $size); return $font; }}Vendor_name\Module_name\Model\Order\Pdf\Shipment.php 同上; ...

May 10, 2019 · 1 min · jiezi