<h5 style="color:red;">系统学习magento二次开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank">《Magento中文全栈二次开发 》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230218/bb9c82995c24d1105676e02f373755f5.jpg" alt="Magento中文全栈二次开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。</p> </div> <hr><p>在Magento 2中为每个订单自动生成CSV文件的步骤:</p><p>步骤1:转到下面的文件路径</p><p>app\code\Vendor\Extension\etc\events.xml</p><p>然后,按如下方式添加代码</p><pre class="brush:bash;toolbar:false"><?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='sales_order_place_after'> <observer name='sales_order_place_after' instance='Vendor\Extension\Observer\GenerateCSV' /> </event> </config></pre><p>步骤2:下一步移至以下文件路径</p><p>app\code\Vendor\Extension\Observer\GenerateCSV.php</p><p>然后添加以下代码片段</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\App\Filesystem\DirectoryList; class GenerateCSV implements ObserverInterface { protected $_objectManager; private $logger; private $productFactory; public function __construct( \Magento\Framework\ObjectManagerInterface $objectManager, \Psr\Log\LoggerInterface $logger, \Magento\Catalog\Model\ProductFactory $productFactory, \Magento\Framework\Filesystem $filesystem) { $this->_objectManager = $objectManager; $this->logger = $logger; $this->productFactory = $productFactory; $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); } public function execute(\Magento\Framework\Event\Observer $observer) { $order = $observer->getEvent()->getOrder(); $order_id = $order->getIncrementId(); $customerfirstname = $order->getCustomerFirstname(); $customerlastname = $order->getCustomerLastname(); $filepath = 'export/'.$order_id.'.csv'; $this->directory->create('export'); $stream = $this->directory->openFile($filepath, 'w+'); $stream->lock(); $header = ['Order Id', 'Customer FirstName', 'Customer LastName']; $stream->writeCsv($header); $data[] = $order_id; $data[] = $customerfirstname; $data[] = $customerlastname; $stream->writeCsv($data); } }</pre><p>步骤3:之后运行以下命令</p><pre class="brush:bash;toolbar:false">php bin/magento setup:di:compile php bin/magento cache:flush</pre><p>您可以看到为Magento 2商店中下的每个订单生成如下所示的CSV。</p><p>结论:</p><p>通过这种方式,您可以在Magento 2中的每个订单上自动生成CSV文件。 在Magento 2中生成订单报告,以轻松管理发货和交付。</p><p><br/></p>
文章列表
<h5 style="color:red;">系统学习magento二次开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank">《Magento中文全栈二次开发 》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230218/bb9c82995c24d1105676e02f373755f5.jpg" alt="Magento中文全栈二次开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。</p> </div> <hr><p>步骤在Magento 2的产品列表页面上添加额外的类别描述:</p><p>步骤1: 首先我们需要 在安装程序文件夹中创建描述属性.php文件</p><p>app\code\Vendor\Extension\Setup\Patch\Data</p><p>现在添加代码,如下所示</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Setup\Patch\Data; use Magento\Eav\Setup\EavSetupFactory; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\Patch\DataPatchInterface; use Magento\Framework\Setup\Patch\PatchRevertableInterface; use Magento\Store\Model\Store; class DescriptionAttribute implements DataPatchInterface { private $eavSetupFactory; /** * Constructor * * @param \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory */ public function __construct(EavSetupFactory $eavSetupFactory, ModuleDataSetupInterface $moduleDataSetup) { $this->eavSetupFactory = $eavSetupFactory; $this->setup = $moduleDataSetup; } /** * {@inheritdoc} */ public function apply() { $eavSetup = $this->eavSetupFactory->create(['setup' => $this->setup]); $eavSetup->addAttribute( \Magento\Catalog\Model\Category::ENTITY, 'extra_description', [ 'type' => 'text', 'label' => 'Extra Description', 'input' => 'textarea', 'required' => false, 'sort_order' => 8, 'global' => ScopedAttributeInterface::SCOPE_STORE, 'wysiwyg_enabled' => true, 'is_html_allowed_on_front' => true, 'group' => 'General Information', ] ); } public static function getDependencies() { return []; } /** * {@inheritdoc} */ public function getAliases() { return []; } /** * {@inheritdoc} */ public static function getVersion() { return '1.0.0'; } }</pre><p>步骤2:下一步,我们需要 在view文件夹中创建category_form.xml文件</p><p>app\code\Vendor\Extension\view\adminhtml\ui_component </p><p>并添加以下代码片段</p><pre class="brush:bash;toolbar:false"><?xml version="1.0" ?> <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"> <fieldset name="content"> <field name="extra_description" template="ui/form/field" sortOrder="50" formElement="wysiwyg"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="wysiwygConfigData" xsi:type="array"> <item name="height" xsi:type="string">100px</item> <item name="add_variables" xsi:type="boolean">false</item> <item name="add_widgets" xsi:type="boolean">false</item> <item name="add_images" xsi:type="boolean">true</item> <item name="add_directives" xsi:type="boolean">true</item> </item> <item name="source" xsi:type="string">category</item> </item> </argument> <settings> <label translate="true">Extra Description</label> <dataScope>extra_description</dataScope> </settings> <formElements> <wysiwyg class="Magento\Catalog\Ui\Component\Category\Form\Element\Wysiwyg"> <settings> <rows>8</rows> <wysiwyg>true</wysiwyg> </settings> </wysiwyg> </formElements> </field> </fieldset> </form></pre><p>步骤3:之后,我们需要 在以下路径中创建extra_description.phtml文件</p><p>app\code\Vendor\Extension\view\frontend\templates\product\list </p><p>然后添加下面提到的代码</p><p><br/></p><pre class="brush:bash;toolbar:false"><?php if ($_bottomDescription = $block->getCurrentCategory()->getExtraDescription()): ?> <div class="category-extra-description"> <?= /* @escapeNotVerified */ $this->helper('Magento\Catalog\Helper\Output')->categoryAttribute($block->getCurrentCategory(), $_bottomDescription, 'extra_description') ?> </div> <?php endif; ?></pre><p>步骤4:在最后一步中,我们需要在 以下路径创建catalog_category_view.xml</p><p>app\code\Vendor\Extension\view\frontend\layout</p><p>现在添加代码,如下所示</p><pre class="brush:bash;toolbar:false"><?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="content"> <block class="Magento\Catalog\Block\Category\View" name="extra.description" template="Vendor_Extension::product/list/extra_description.phtml" after="-"/> </referenceContainer> </body> </page></pre><p>结论:</p><p>现在,您可以在Magento 2的产品列表页面上轻松添加有关该类别的更多信息。</p><p><br/></p>
<h5 style="color:red;">系统学习magento二次开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank">《Magento中文全栈二次开发 》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230218/bb9c82995c24d1105676e02f373755f5.jpg" alt="Magento中文全栈二次开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。</p> </div> <hr><p>步骤1:在以下路径创建博客文件“索引.php”</p><p>app/code/Vendor/Extension/Block/Index</p><p>然后添加代码,如下所示</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Block\Index; class Index extends \Magento\Framework\View\Element\Template { public function __construct(\Magento\Catalog\Block\Product\Context $context, array $data = []) { parent::__construct($context, $data); } protected function _prepareLayout() { return parent::_prepareLayout(); } }</pre><p>步骤 2:在以下路径创建控制器文件“索引.php”</p><p>app/code/Vendor/Extension/Controller/Index</p><p>然后添加以下代码片段</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Controller\Index; class Index extends \Magento\Framework\App\Action\Action { public function execute() { $this->_view->loadLayout(); $this->_view->getLayout()->initMessages(); $this->_view->renderLayout(); } }</pre><p>第 3 步:在以下路径创建控制器文件.php</p><p>app/code/Vendor/Extension/Controller/Index/Post.php</p><p>然后添加以下代码片段</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Controller\Index; use Magento\Store\Model\StoreManagerInterface; class Post extends \Magento\Framework\App\Action\Action { protected $_inlineTranslation; protected $_transportBuilder; protected $_scopeConfig; protected $_logLoggerInterface; protected $storeManager; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation, \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Psr\Log\LoggerInterface $loggerInterface, StoreManagerInterface $storeManager, array $data = [] ) { $this->_inlineTranslation = $inlineTranslation; $this->_transportBuilder = $transportBuilder; $this->_scopeConfig = $scopeConfig; $this->_logLoggerInterface = $loggerInterface; $this->messageManager = $context->getMessageManager(); $this->storeManager = $storeManager; parent::__construct($context); } public function execute() { try { $post = $this->getRequest()->getPost(); // Send Mail $this->_inlineTranslation->suspend(); $sender = [ 'name' => $post['name'], 'email' => $post['email'] ]; $transport = $this->_transportBuilder ->setTemplateIdentifier('customemail_email_template') ->setTemplateOptions( [ 'area' => 'frontend', 'store' => $this->storeManager->getStore()->getId() ] ) ->setTemplateVars([ 'name2' => $post['name'], 'email2' => $post['email'] ]) ->setFromByScope($sender) ->addTo($post['email'],$post['name']) ->getTransport(); $transport->sendMessage(); $this->_inlineTranslation->resume(); $this->messageManager->addSuccess('Email sent successfully'); $this->_redirect('email/index/index'); } catch(\Exception $e){ $this->messageManager->addErrorMessage("Something Went Wrong"); } } }</pre><p>步骤 4:为以下路径的正面表单显示创建一个“email_index_index.xml”文件</p><p>app/code/Vendor/Extension/view/frontend/layout</p><p>然后添加以下代码段</p><pre class="brush:bash;toolbar:false"><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd"> <head> <title>Inquiery Form</title> </head> <body> <referenceContainer name="content"> <block class="Vendor\Extension\Block\Index\Index" name="customermail_index_index" template="Vendor_Extension::form.phtml"/> </referenceContainer> </body> </page></pre><p>步骤 5:在以下路径创建表单模板“form.phtml”</p><p>app/code/Vendor/Extension/view/frontend/templates</p><p>现在添加以下代码片段</p><pre class="brush:bash;toolbar:false"><form enctype="multipart/form-data" action="<?php echo $block->getBaseUrl().'email/index/post/';?>" name="customemaildata" method="post" id="contactForm-1" data-hasrequired="<?php echo __('* Required Fields') ?>" data-mage-init='{"validation":{}}'> <fieldset class="fieldset"> <div class="field email required"> <label class="label" for="email"> Product Name :-</label> <div class="control"> <select name="name" id="name"> <option value="0">Please Select</option> <option value="1">Product - 1</option> <option value="2">Product - 2</option> <option value="3">Product - 3</option> <option value="4">Product - 4</option> <option value="5">Product - 5</option> </select> </div> </div> <div class="field email required"> <label class="label" for="email">Email:-</label> <div class="control"> <input name="email" id="email" class="input-text" type="email" data-validate="{required:true, 'validate-email':true}"/> </div> </div> </fieldset> <div class="actions-toolbar"> <div class="primary"> <input type="hidden" name="hideit" id="hideit" value="" /> <button type="submit" title="<?php echo __('Submit') ?>" class="action submit primary"> <span><?php echo __('Submit') ?></span> </button> </div> </div> </form></pre><p>步骤 6: 在以下路径创建电子邮件模板布局文件“email_templates.xml”</p><p>app/code/Vendor/Extension/etc</p><p>现在添加以下代码</p><pre class="brush:bash;toolbar:false"><?xml version="1.0" encoding="UTF-8"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd"> <template id="customemail_email_template" label="Email Form" file="customeremail.html" type="html" module="Vendor_Extension" area="frontend"/> </config></pre><p>第 7 步:在下面的路径上创建一个电子邮件 html 文件“客户电子邮件.html”</p><p>app/code/Vendor/Extension/view/frontend/email</p><p>然后附加下面给出的代码</p><pre class="brush:bash;toolbar:false"><body style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;"> <div style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;"> <table cellspacing="0" cellpadding="0" border="0" height="100%" width="100%"> <tr> <tr> <td valign="top" colspan="5"> <p style="border:1px solid #E0E0E0; font-size:12px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9; text-align:center;"><strong>Product Information</strong></td> </tr> <!-- Method- 1 --> {{depend name}} <tr> <td> <p style="border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;">product Id :- {{var name}} </p> </td> </tr> {{/depend}} <!-- Method - 1 --> <!-- Method- 2 --> {{if email}} <tr> <td> <p style="border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;"> {{var email}} if condition</p> </td> </tr> {{/if}} <!-- Method- 2--> <!-- Method- 3 --> {{block class='Magento\\Framework\\View\\Element\\Template' area='frontend' template='Vendor_Extension::productinformation.phtml' name=$name}} <!-- Method- 3 --> </table> </td> </tr> </table> </div> </body></pre><p>步骤 8:在以下路径为条件值创建模板文件“productinformation.phtml”</p><p>app/code/Vendor/Extension/view/frontend/templates</p><p>最后,添加以下代码</p><pre class="brush:bash;toolbar:false"><?php switch ($this->getData('name')) { case "0": echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> No Product Selected</p></td></tr>" ; break; case "1": echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> Product 1 Is Selected</p></td></tr>" ; echo "<p> </p>" ; break; case "2": echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> Product 2 Is Selected</p></td></tr>" ; break; case "3": echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> Product 3 Is Selected</p></td></tr>" ; break; case "4": echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> Product 4 Is Selected</p></td></tr>" ; break; case "5": echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> Product 5 Is Selected</p></td></tr>" ; break; default: echo "<tr><td><p style='border:1px solid #E0E0E0; font-size:14px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;'> No Record Found</p></td></tr>" ; }</pre><p>结论:</p><p>通过实施上述步骤,您可以轻松地在Magento 2电子邮件模板中包含条件语句。</p><p><br/></p>
<h5 style="color:red;">系统学习magento二次开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank">《Magento中文全栈二次开发 》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230218/bb9c82995c24d1105676e02f373755f5.jpg" alt="Magento中文全栈二次开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。</p> </div> <hr><p>在Magento 2中添加自定义字段并在产品属性中添加表单中添加值的步骤:</p><p>第1步: 首先我们需要在 etc文件夹中创建一个“di.xml”文件</p><p>app\code\Vendor\Extension\etc\adminhtml</p><p>现在,添加代码,如下所示</p><pre class="brush:bash;toolbar:false"><?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\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Front"> <plugin name="extension_attribute_edit_form" type="Vendor\Extension\Plugin\Block\Adminhtml\Product\Attribute\Edit\Tab\Front" sortOrder="1"/> </type> </config></pre><p>步骤2: 在下一步中,我们将在 插件文件夹中创建“Front.php”文件</p><p>app\code\Vendor\Extension\Plugin\Block\Adminhtml\Product\Attribute\Edit\Tab</p><p>然后附加下面提到的代码片段</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Plugin\Block\Adminhtml\Product\Attribute\Edit\Tab; class Front { protected $custom; public function __construct( \Magento\Config\Model\Config\Source\Yesno $custom ) { $this->custom = $custom; } public function aroundGetFormHtml( \Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Front $subject, \Closure $proceed ) { $customSource = $this->custom->toOptionArray(); $form = $subject->getForm(); $fieldset = $form->getElement('front_fieldset'); $fieldset->addField( 'used_in_custom', 'select', [ 'name' => 'used_in_custom', 'label' => __('Used in Custom'), 'title' => __('Used in Custom'), 'values' => $customSource, ] ); return $proceed(); } }</pre><p>步骤3:然后我们将 在etc文件夹中创建“db_schema.xml”文件</p><p>app\code\Vendor\Extension\etc</p><p>最后,添加以下代码</p><pre class="brush:bash;toolbar:false"><schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="catalog_eav_attribute" resource="default" engine="innodb" comment="Catalog EAV Attribute Table"> <column xsi:type="smallint" name="used_in_custom" unsigned="true" nullable="false" identity="false" default="0" comment="Custom forms"/> </table> </schema></pre><p>输出:</p><p><img src="/uploads/images/20230830/b86d05246ab0407b937275b32f022a6c.png" title="1.png" alt=""/></p><p>自定义产品字段</p><p>结论:</p><p>这样,您可以在Magento 2中添加自定义字段并在产品属性中添加表单中保存值。</p><p><br/></p>
<h5 style="color:red;">系统学习magento二次开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank">《Magento中文全栈二次开发 》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230218/bb9c82995c24d1105676e02f373755f5.jpg" alt="Magento中文全栈二次开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。</p> </div> <hr><p>在Magento 2的“管理订单视图”页面中添加可编辑字段的步骤:</p><p>步骤1:转到以下文件路径</p><p>app\code\Vendor\Extension\view\adminhtml\layout\sales_order_view.xml</p><p>然后添加以下代码</p><pre class="brush:bash;toolbar:false"><?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="order_additional_info"> <block class="Vendor\Extension\Block\Adminhtml\Order\Checkoutcustomformedit" name="admin.chekoutcustomfield" template="Vendor_Extension::checkoutcustomformedit.phtml" /> </referenceBlock> </body> </page></pre><p>步骤2:接下来,移动到以下文件路径</p><p>app\code\Vendor\Extension\Block\Adminhtml\Order\Checkoutcustomformedit.php</p><p>现在添加下面提到的代码片段</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Block\Adminhtml\Order; use \Magento\Backend\Block\Template; use \Magento\Backend\Block\Template\Context; use \Magento\Sales\Model\Order; class Checkoutcustomformedit extends Template { protected $order; public function __construct( Context $context, Order $order, array $data = []) { $this->order = $order; parent::__construct($context, $data); } public function getOrderId() { $orderId = $this->getRequest()->getParam('order_id'); return $orderId; } public function getCustomfieldvalue() { $orderId = $this->getOrderId(); $customfieldvalue = $this->order->load($orderId)->getData('customfield1'); return $customfieldvalue; } }</pre><p>步骤3:现在导航到以下文件路径</p><p>app\code\Vendor\Extension\view\adminhtml\templates\Checkoutcustomformedit.phtml</p><p>现在添加代码,如下所示</p><pre class="brush:bash;toolbar:false"><section class="admin__page-section"> <div class="admin__page-section-title"> <span class="title"> <?php /* @escapeNotVerified */ echo __('Buyer Order Information') ?> </span> <div id="checkoutfield-edit-link" class="actions block-edit-link"> <a href="#" id="edit-checkoutfield-info"> <?= $block->escapeHtml(__('Edit')); ?> </a> </div> </div> <div class="admin__page-section-content"> <div class="order-information textfied" id="textfiedcustomfield"> <div class="box"> <div class="box-content"> <?php echo $block->getCustomfield1(); ?> </div> </div> </div> </div> <div class="admin__page-section-item-content edit-checkoutfield-date" id="edit-checkoutfield-info-form" style="display: none;"> <fieldset class="admin__fieldset"> <input type="hidden" id="orderid" value="<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $request = $objectManager->get('Magento\Framework\App\Request\Http'); echo $param = $request->getParam('order_id');?>"/> <input type="text" id="customfield1" class="customfield1" value="<?php echo $block->getCustomfield1(); ?>"> </fieldset> <button id="customfield-submit">Submit</button> </div> </section> <script type="text/javascript"> require([ 'jquery', 'mage/validation', 'mage/translate', 'jquery/ui' ], function ($) { document.getElementById('edit-checkoutfield-info').addEventListener('click', function (e, t) { e.preventDefault(); $('#edit-checkoutfield-info-form').toggle(); }); $("#customfield-submit").click(function() { var orderid = $('#orderid').val(); if($('#customfield1').length){ var customfield1 = $('#customfield1').val(); } var url = '<?= /** @noEscape */ $block->getUrl("groupproduct/queue/update")?>'; jQuery.ajax({ url: url, data: {orderid: orderid,customfield1value: customfield1}, type: "POST", async: false, }).done(function (response) { $("#textfiedcustomfield").load(location.href + " #textfiedcustomfield"); }); }); }); </script></pre><p>步骤4:最后,移动到以下文件路径</p><p>app\code\Vendor\Extension\Controller\Adminhtml\Queue\Update.php</p><p>并添加下面提到的代码</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Controller\Adminhtml\Queue; use Magento\Framework\App\ResponseInterface; use Magento\Framework\Exception\LocalizedException; use Magento\Backend\App\Action; use Magento\Sales\Api\OrderRepositoryInterface; class Update extends Action { protected $quoteFactory protected $orderinterface; protected $request; public function __construct( Action\Context $context, \Magento\Quote\Model\QuoteFactory $quoteFactory, \Magento\Sales\Api\Data\OrderInterface $orderinterface, \Magento\Framework\App\Request\Http $request) { parent::__construct($context); $this->orderinterface = $orderinterface; $this->request = $request; $this->quoteFactory = $quoteFactory; } public function execute() { $customfield1value = $this->getRequest()->getPostValue('customfield1value'); $orderid = $this->getRequest()->getPostValue('orderid'); $order = $this->orderinterface->load($orderid); $order->setData('customfield1', $customfield1value); $order->save(); } }</pre><p>结论:</p><p>这样,您可以在Magento 2的管理订单视图页面中添加可编辑字段。</p><p><br/></p>
<h5 style="color:red;">系统学习magento二次开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank">《Magento中文全栈二次开发 》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230218/bb9c82995c24d1105676e02f373755f5.jpg" alt="Magento中文全栈二次开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。</p> </div> <hr><p>删除Magento 2中的现有管理菜单:</p><p>步骤 1:在模块中按以下路径创建布局文件</p><p>app\code\Vendor\Extension\etc\adminhtml\menu.xml</p><p>在此文件中,使用以下代码按菜单的 id 删除菜单。</p><pre class="brush:bash;toolbar:false"><?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd"> <menu> <remove id="Magento_Customer::customer_online" /> </menu> </config></pre><p>在这里,我们从“客户”菜单中删除了“现在在线”。您可以在下图中看到菜单已被删除。</p><p><img src="/uploads/images/20230830/b293b47abc6df8674e85e3b4cc941d1d.png" title="1.png" alt="" width="864" height="426"/></p><p>删除现有菜单</p><p>结论:</p><p>您可以轻松更新或删除Magento 2中的管理菜单。</p><p><br/></p>
<h5 style="color:red;">系统学习magento二次开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank">《Magento中文全栈二次开发 》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230218/bb9c82995c24d1105676e02f373755f5.jpg" alt="Magento中文全栈二次开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。</p> </div> <hr><p>在Magento 2中获取所有网站的所有商店的步骤:</p><p>步骤1:转到以下文件路径</p><p>app\code\Vendor\Extension\etc\di.xml</p><p>然后添加代码,如下所示</p><pre class="brush:bash;toolbar:false"><?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Magento\Store\Block\Switcher" type="Vendor\Extension\Block\Switcher"/> </config></pre><p>步骤2:现在移动到以下文件路径</p><p>app\code\Vendor\Extension\Block\Switcher.php</p><p>之后添加以下代码片段</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Block; use Magento\Directory\Helper\Data; use Magento\Store\Model\Group; use Magento\Store\Model\Store; use Magento\Framework\App\ActionInterface; use Magento\Framework\App\ObjectManager; use Magento\Framework\Url\Helper\Data as UrlHelper; /** * Switcher block * * @api * @since 100.0.2 */ class Switcher extends \Magento\Store\Block\Switcher { /** * @var bool */ protected $_storeInUrl; /** * @var \Magento\Framework\Data\Helper\PostHelper */ protected $_postDataHelper; /** * @var UrlHelper */ private $urlHelper; /** * @param \Magento\Framework\View\Element\Template\Context $context * @param \Magento\Framework\Data\Helper\PostHelper $postDataHelper * @param array $data * @param UrlHelper $urlHelper */ public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Data\Helper\PostHelper $postDataHelper, array $data = [], \Magento\Framework\Url\Helper\Data $urlHelper = null ) { $this->_postDataHelper = $postDataHelper; parent::__construct($context, $postDataHelper, $data); $this->urlHelper = $urlHelper ?: ObjectManager::getInstance()->get(\Magento\Framework\Url\Helper\Data::class); } /** * @return array */ public function getRawAllStores() { $websites = $this->_storeManager->getWebsites(); $stores = []; foreach ($websites as $website) { $websiteStores = $website->getStores(); foreach ($websiteStores as $store) { /* @var $store \Magento\Store\Model\Store */ if (!$store->isActive()) { // continue; } $localeCode = $this->_scopeConfig->getValue( Data::XML_PATH_DEFAULT_LOCALE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store ); $store->setLocaleCode($localeCode); $params = ['_query' => []]; if (!$this->isStoreInUrl()) { $params['_query']['___store'] = $store->getCode(); } $baseUrl = $store->getUrl('', $params); $store->setHomeUrl($baseUrl); $stores[$store->getGroupId()][$store->getId()] = $store; } } return $stores; } }</pre><p>步骤3:最后,运行以下命令</p><pre class="brush:bash;toolbar:false">php bin/magento setup:di:compile php bin/magento cache:flush</pre><p>结论:</p><p>因此,借助此方法,您可以获取Magento 2商店所有网站的所有商店列表。</p><p><br/></p>
<h5 style="color:red;">系统学习magento二次开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank">《Magento中文全栈二次开发 》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230218/bb9c82995c24d1105676e02f373755f5.jpg" alt="Magento中文全栈二次开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。</p> </div> <hr><p>在Magento 2中以编程方式创建优惠券代码的步骤:</p><p>步骤1: 您需要在Magento根目录上创建一个根脚本文件。</p><p>文件路径:Root Directory\pub\Customcoupon.php</p><p>现在添加以下代码</p><pre class="brush:bash;toolbar:false"><?php use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $params = $_SERVER; $bootstrap = Bootstrap::create(BP, $params); $obj = $bootstrap->getObjectManager(); $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('adminhtml'); $coupon['name'] = 'custom_coupon'; $coupon['desc'] = ' 10% Off Discount coupon.'; $coupon['start'] = date('Y-m-d'); $coupon['end'] = ''; $coupon['max_redemptions'] = 1; $coupon['discount_type'] ='by_percent'; $coupon['discount_amount'] = 10; $coupon['flag_is_free_shipping'] = 'no'; $coupon['redemptions'] = 1; $coupon['code'] ='10%OFF'; $shoppingCartPriceRule = $obj->create('Magento\SalesRule\Model\Rule'); $shoppingCartPriceRule->setName($coupon['name']) ->setDescription($coupon['desc']) ->setFromDate($coupon['start']) ->setToDate($coupon['end']) ->setUsesPerCustomer($coupon['max_redemptions']) ->setCustomerGroupIds(array('0','1','2','3',)) ->setIsActive(1) ->setSimpleAction($coupon['discount_type']) ->setDiscountAmount($coupon['discount_amount']) ->setDiscountQty(1) ->setApplyToShipping($coupon['flag_is_free_shipping']) ->setTimesUsed($coupon['redemptions']) ->setWebsiteIds(array('1')) ->setCouponType(2) ->setCouponCode($coupon['code']) ->setUsesPerCoupon(NULL); $shoppingCartPriceRule->save();</pre><p>现在,从Magento 2管理面板中检查优惠券代码。</p><p><img src="/uploads/images/20230830/28fdde79be11d3586bd4126edfedbf9d.png" title="1.png" alt="" width="800" height="379"/></p><p>优惠券代码</p><p>结论:</p><p>这样,您可以轻松地在Magento 2中以编程方式创建优惠券代码。</p><p><br/></p>
<h5 style="color:red;">系统学习magento二次开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank">《Magento中文全栈二次开发 》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230218/bb9c82995c24d1105676e02f373755f5.jpg" alt="Magento中文全栈二次开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。</p> </div> <hr><p>在Magento 2中结帐页面字段中添加占位符文本的步骤:</p><p>步骤1:首先 在给定的以下路径创建di.xml文件</p><p>app/code/vendor/extension/etc/frontend/di.xml</p><p>现在添加代码,如下所示</p><pre class="brush:bash;toolbar:false"><?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\Block\Checkout\AttributeMerger"> <pluginname="add_placeholderto_checkout" type="Vendor\Extension\Plugin\Block\Checkout\AttributeMerger" sortOrder="10"/> </type> </config></pre><p>第 2 步:现在在以下路径创建一个插件文件</p><p>app/code/Vendor/Extension/Plugin/ Block/ Checkout/ AttributeMerger.php</p><p>然后添加以下代码</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Plugin\Block\Checkout; class AttributeMerger { public function afterMerge(\Magento\Checkout\Block\Checkout\AttributeMerger $subject,$result) { $result['firstname']['placeholder'] = __('First Name'); $result['lastname']['placeholder'] = __('Last Name'); $result['street']['children'][0]['placeholder'] = __('Line no 1'); $result['street']['children'][1]['placeholder'] = __('Line no 2'); $result['city']['placeholder'] = __('Enter City'); $result['postcode']['placeholder'] = __('Enter Zip/Postal Code'); $result['telephone']['placeholder'] = __('Enter Phone Number'); return $result; } }</pre><p>最后,清除缓存并检查结帐页面上的输出。</p><p>结论:</p><p>这样,您可以轻松地在Magento 2结帐页面的各个字段中添加占位符文本。</p><p><br/></p>
<h5 style="color:red;">系统学习magento二次开发,推荐小册:<a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank">《Magento中文全栈二次开发 》</a></h5> <div class="image-container"> <p> <a style="color:blue;" href="https://www.maxiaoke.com/manual/magento_cn_dev.html" target="_blank"> <img src="https://www.maxiaoke.com/uploads/images/20230218/bb9c82995c24d1105676e02f373755f5.jpg" alt="Magento中文全栈二次开发"> </a> </p> </div> <div class="text-container" style="font-size:14px; color:#888"> <p>本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。</p> </div> <hr><p>在Magento 2中的订单电子邮件中添加下载发票按钮的步骤:</p><p>步骤1:首先,转到以下文件路径</p><p>app\code\Vendor\Extension\view\frontend\layout\sales_email_order_items.xml</p><p>然后添加代码,如下所示</p><pre class="brush:bash;toolbar:false"><?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" label="Email Order Items List" design_abstraction="custom"> <body> <referenceBlock name="items"> <action method="setTemplate"> <argument name="template" translate="true" xsi:type="string">Vendor_Extension::email/items.phtml</argument> </action> </referenceBlock> </body> </page></pre><p>步骤2:接下来,移至文件路径,如下所示</p><p>app\code\Vendor\Extension\view\frontend\templates\email\items.phtml</p><p></p><pre class="brush:bash;toolbar:false"><?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ // phpcs:disable Magento2.Templates.ThisInTemplate /** @var $block \Magento\Sales\Block\Order\Email\Items */ ?> <?php $_order = $block->getOrder() ?> <?php if ($_order) : ?> <?php $_items = $_order->getAllItems(); ?> <?php foreach ($_items as $_item) : ?> <?php if (!$_item->getParentItem()) : ?> <?= $block->getItemHtml($_item) ?> <?php endif; ?> <?php endforeach; ?> <tr> <td style="font-size: 18px;font-weight: bold;border-bottom: 1px solid #ccc;padding-bottom: 10px;font-family: Arial, Helvetica, sans-serif;"> Order Total </td> </tr> <tr class="order-totals"> <?= $block->getChildHtml('order_totals') ?> </tr> <?php if(count($_order->getInvoiceCollection())): $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $store = $storeManager->getStore(); $baseUrl = $store->getBaseUrl(); ?> <tr> <td style="text-align: center;font-family: Arial, Helvetica, sans-serif;"> <a href="<?= $baseUrl ?>emailcustomisation/invoice/printinvoice/order_id/<?= $_order->getId() ?>" class="download" >Download </a> </td> </tr> <?php endif; ?> <?php if ($this->helper(\Magento\GiftMessage\Helper\Message::class) ->isMessagesAllowed('order', $_order, $_order->getStore()) && $_order->getGiftMessageId() ) : ?> <?php $_giftMessage = $this->helper(\Magento\GiftMessage\Helper\Message::class) ->getGiftMessage($_order->getGiftMessageId()); ?> <?php if ($_giftMessage) : ?> <br /> <table class="message-gift"> <tr> <td> <h3><?= $block->escapeHtml(__('Gift Message for this Order')) ?></h3> <strong><?= $block->escapeHtml(__('From:')) ?></strong> <?= $block->escapeHtml($_giftMessage->getSender()) ?> <br /><strong><?= $block->escapeHtml(__('To:')) ?></strong> <?= $block->escapeHtml($_giftMessage->getRecipient()) ?> <br /><strong><?= $block->escapeHtml(__('Message:')) ?></strong> <br /><?= $block->escapeHtml($_giftMessage->getMessage()) ?> </td> </tr> </table> <?php endif; ?> <?php endif; ?> <?php endif; ?></pre><p>步骤3:现在导航到以下文件路径</p><p>app\code\Vendor\Extension\etc\frontend\routes.xml</p><pre class="brush:bash;toolbar:false"><?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="standard"> <route id="yourrouteid" frontName="yourfrountname"> <module name="Vendor_Extension" /> </route> </router> </config></pre><p>步骤4:接下来,您需要转到下面提到的文件路径</p><p>app\code\Vendor\Extension\Controller\Invoice\Printinvoice.php</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Controller\Invoice; use Magento\Framework\App\ResponseInterface; use Magento\Framework\App\Filesystem\DirectoryList; class Printinvoice extends \Magento\Framework\App\Action\Action { /** * Authorization level of a basic admin session * * @see _isAllowed() */ const ADMIN_RESOURCE = 'Magento_Sales::sales_invoice'; /** * @var \Magento\Framework\App\Response\Http\FileFactory */ protected $_fileFactory; /** * @var \Magento\Backend\Model\View\Result\ForwardFactory */ protected $resultForwardFactory; /** * @param \Magento\Backend\App\Action\Context $context * @param \Magento\Framework\App\Response\Http\FileFactory $fileFactory * @param \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory */ public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\App\Response\Http\FileFactory $fileFactory, \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory, \Magento\Sales\Model\OrderFactory $order) { $this->_fileFactory = $fileFactory; parent::__construct($context); $this->resultForwardFactory = $resultForwardFactory; $this->order = $order; } /** * @return ResponseInterface|void * @throws \Exception */ public function execute() { $orderId = $this->getRequest()->getParam('order_id'); $orderdetails = $this->order->create()->load($orderId); $invoiceId = 0; foreach ($orderdetails->getInvoiceCollection() as $invoice) { $invoiceId = $invoice->getId(); } if ($invoiceId != 0) { $invoice = $this->_objectManager->create( \Magento\Sales\Api\InvoiceRepositoryInterface::class )->get($invoiceId); if ($invoice) { $pdf = $this->_objectManager->create(\Magento\Sales\Model\Order\Pdf\Invoice::class)->getPdf([$invoice]); $date = $this->_objectManager->get( \Magento\Framework\Stdlib\DateTime\DateTime::class )->date('Y-m-d_H-i-s'); $fileContent = ['type' => 'string', 'value' => $pdf->render(), 'rm' => true]; return $this->_fileFactory->create( 'invoice' . $date . '.pdf', $fileContent, DirectoryList::VAR_DIR, 'application/pdf' ); } } else { return; return $this->resultForwardFactory->create()->forward('noroute'); } } }</pre><p>步骤5:在此步骤中,移至以下文件路径</p><p>app\code\Vendor\Extension\Model\Order\Pdf\Invoice.php</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Model\Order\Pdf; use PHPQRCode\QRcode; class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice { protected function _setFontBold($object, $size = 7) { $font = \Zend_Pdf_Font::fontWithPath($this->getFontPath()); $object->setFont($font, $size); return $font; } public function newPage(array $settings = []) { $page = $this->_getPdf()->newPage(\Zend_Pdf_Page::SIZE_A4); $this->_getPdf()->pages[] = $page; $this->y = 800; if (!empty($settings['table_header'])) { $this->_drawHeader($page); } return $page; } protected function _drawHeader(\Zend_Pdf_Page $page) { $this->_setFontRegular($page, 10); $page->setFillColor(new \Zend_Pdf_Color_RGB(0.93, 0.92, 0.92)); $page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5)); $page->setLineWidth(0.5); $page->drawRectangle(25, $this->y, 570, $this->y - 15); $this->y -= 10; $page->setFillColor(new \Zend_Pdf_Color_RGB(0, 0, 0)); $taxableAmountText = $this->string->split('Taxable Amount', 8); $lines[0][] = ['text' => __('Products'), 'feed' => 35]; $lines[0][] = ['text' => __('Qty'), 'feed' => 150, 'align' => 'right']; $lines[0][] = ['text' => __('Price'), 'feed' => 185, 'align' => 'right']; $lines[0][] = ['text' => __('Subtotal'), 'feed' => 235, 'align' => 'right']; $lines[0][] = ['text' => __('Discount'), 'feed' => 290, 'align' => 'right']; $lines[0][] = ['text' => __('Tax Amt'), 'feed' => 345, 'align' => 'right']; $lines[0][] = ['text' => __('Custom'), 'feed' => 400, 'align' => 'right']; $lines[0][] = ['text' => __('Row Total'), 'feed' => 570, 'align' => 'right']; $lineBlock = ['lines' => $lines, 'height' => 5, $this->y]; $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]); $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0)); $this->y -= 20; } protected function _setFontRegular($object, $size = 7) { $font = \Zend_Pdf_Font::fontWithPath($this->getFontPath()); $object->setFont($font, $size); return $font; } protected function _drawFooter(\Zend_Pdf_Page $page) { $this->_setFontRegular($page, 10); $this->y -= 10; $page->setFillColor(new \Zend_Pdf_Color_RGB(0, 0, 0)); } protected function _setFontItalic($object, $size = 7) { $font = \Zend_Pdf_Font::fontWithPath($this->getFontPath()); $object->setFont($font, $size); return $font; } }</pre><p>步骤6:最后,转到以下文件路径</p><p>app\code\Vendor\Extension\Model\Sales\Order\Pdf\Items\Invoice.php</p><pre class="brush:bash;toolbar:false"><?php namespace Vendor\Extension\Model\Sales\Order\Pdf\Items; use Magento\Bundle\Model\Sales\Order\Pdf\Items\Invoice as InvoiceDefualt; class Invoice extends InvoiceDefualt { public function draw() { $draw = $this->drawChildrenItems(); $draw = $this->drawCustomOptions($draw); $page = $this->getPdf()->drawLineBlocks($this->getPage(), $draw, ['table_header' => true]); $this->setPage($page); } private function drawChildrenItems(): array { $this->_setFontRegular(); $prevOptionId = ''; $drawItems = []; $optionId = 0; $lines = []; foreach ($this->getChildren($this->getItem()) as $childItem) { $index = array_key_last($lines) !== null ? array_key_last($lines) + 1 : 0; $attributes = $this->getSelectionAttributes($childItem); if (is_array($attributes)) { $optionId = $attributes['option_id']; } if (!isset($drawItems[$optionId])) { $drawItems[$optionId] = ['lines' => [], 'height' => 15]; } if ($childItem->getOrderItem()->getParentItem() && $prevOptionId != $attributes['option_id']) { $lines[$index][] = [ 'font' => 'italic', 'text' => $this->string->split($attributes['option_label'], 35, true, true), 'feed' => 35, ]; $index++; $prevOptionId = $attributes['option_id']; } if ($childItem->getOrderItem()->getParentItem()) { $feed = 30; $name = $this->getValueHtml($childItem)."<br /> SKU :".$childItem- >getSku(); } else { $feed = 25; $name = $childItem->getName(); } $lines[$index][] = ['text' => $this->string->split($name, 15, true, true), 'feed' => $feed]; if ($this->canShowPriceInfo($childItem)) { $tax = $this->getOrder()->formatPriceTxt($childItem->getTaxAmount()); $item = $this->getItem(); $this->_item = $childItem; $feedPrice = 140; $feedSubtotal = $feedPrice + 185; foreach ($this->getItemPricesForDisplay() as $priceData) { if (isset($priceData['label'])) { // draw Price label $lines[$index][] = ['text' => $priceData['label'], 'feed' => $feedPrice, 'align' => 'right']; // draw Subtotal label $lines[$index][] = ['text' => $priceData['label'], 'feed' => $feedSubtotal, 'align' => 'right']; $index++; } $lines[$index][] = [ 'text' => round($childItem->getQty(), 2), 'feed' => $feedPrice, 'font' => 'bold', 'align' => 'right', ]; // draw Price $lines[$index][] = [ 'text' => $priceData['price'], 'feed' => $feedPrice+40, 'font' => 'bold', 'align' => 'right', ]; // draw Subtotal $lines[$index][] = [ 'text' => $priceData['subtotal'], 'feed' => $feedPrice+90, 'font' => 'bold', 'align' => 'right', ]; $lines[$index][] = [ 'text' => round($childItem->getDiscountAmount(), 2), 'feed' => $feedPrice+130, 'font' => 'bold', 'align' => 'right', ]; $lines[$index][] = [ 'text' => $tax, 'feed' => $feedPrice+200, 'font' => 'bold', 'align' => 'right', ]; $lines[$index][] = [ 'text' => "Custom", 'feed' => $feedPrice+260, 'font' => 'bold', 'align' => 'right', ]; $lines[$index][] = [ 'text' => $this->getOrder()->formatPriceTxt($childItem->getRowTotal()+$childItem->getTaxAmount()), 'feed' => $feedSubtotal+230, 'font' => 'bold', 'align' => 'right', ]; $index++; } $this->_item = $item; } /* drawPrices End */ } $drawItems[$optionId]['lines'] = $lines; return $drawItems; } private function drawCustomOptions(array $draw): array { $options = $this->getItem()->getOrderItem()->getProductOptions(); if ($options && isset($options['options'])) { foreach ($options['options'] as $option) { $lines = []; $lines[][] = [ 'text' => $this->string->split( $this->filterManager->stripTags($option['label']), 40, true, true ), 'font' => 'italic', 'feed' => 35, ]; if ($option['value']) { $text = []; $printValue = $option['print_value'] ?? $this->filterManager->stripTags($option['value']); $values = explode(', ', $printValue); foreach ($values as $value) { foreach ($this->string->split($value, 30, true, true) as $subValue) { $text[] = $subValue; } } $lines[][] = ['text' => $text, 'feed' => 40]; } $draw[] = ['lines' => $lines, 'height' => 15]; } } return $draw; } }</pre><p>步骤7:最后,运行以下命令</p><pre class="brush:bash;toolbar:false">php bin/magento cache:flush php bin/magento setup:di:compile</pre><p>结论:</p><p>借助上述步骤,您可以轻松添加下载发票按钮来订购电子邮件并改善用户体验。</p><p><br/></p>