在Magento 2如何覆盖php或布局核心文件


In Magento 2 How to Override phtml or layout core files?

我在Magento 2中开发了"Hello world"扩展。

我想重写contact Us形式的核心文件。在Magento 2中重写Contact us表单文件的正确方法是什么?

请帮帮我。

与前两个答案不同,我选择从布局中删除原始块,并使用我自己的模板添加新块

我们将创建一个新模块VendorName_ModuleName,我们需要为此创建以下文件:

  1. /app/code/VendorName/ModuleName/view/frontend/layout/contact_index_index.xml
  2. /app/code/VendorName/ModuleName/view/frontend/templates/form.phtml
  3. /app/code/VendorName/ModuleName/etc/module.xml
  4. /app/code/VendorName/ModuleName/composer.json
  5. /app/code/VendorName/ModuleName/registration.php

Magento 2中的每个模块都有唯一的名称,由两部分组成。第一部分是描述构建扩展的公司、个人或团体的单词。这有时被称为"vendor"命名空间。模块名称的第二部分是描述模块功能的单词。

Alan Storm,在他的教程Magento 2 Hello World Module


contact_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">    
    <body>

        <!-- Remove the original Contact Form -->
        <referenceBlock name="contactForm" remove="true"/>

        <!-- Add a custom Contact Form -->
        <referenceContainer name="content">
            <block class="Magento'Contact'Block'ContactForm" name="customContactForm" template="My_Module::form.phtml" />
        </referenceContainer>
    
    </body>
</page>

在上面的代码中,我删除了原始的表单块,并通过在referenceContainer内容中添加我自己的表单来替换它。

注意:

contact_index_index.xml中,代码template="My_Module::form.phtml"指的是自定义联系人表单的phtml


form.phtml

现在,您需要制作自定义表单模板。你可以复制原始文件并对其进行修改。

<form class="form contact"
      action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
      id="contact-form"
      method="post"
      data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
      data-mage-init='{"validation":{}}'>
    <fieldset class="fieldset">
        <legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Write Us') ?></span></legend><br />
        <div class="field note no-label"><?php /* @escapeNotVerified */ echo __('Jot us a note and we’ll get back to you as quickly as possible.') ?></div>
        <div class="field name required">
            <label class="label" for="name"><span><?php /* @escapeNotVerified */ echo __('Name') ?></span></label>
            <div class="control">
                <input name="name" id="name" title="<?php /* @escapeNotVerified */ echo __('Name') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento'Contact'Helper'Data')->getUserName()) ?>" class="input-text" type="text" data-validate="{required:true}"/>
            </div>
        </div>
        <div class="field email required">
            <label class="label" for="email"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
            <div class="control">
                <input name="email" id="email" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento'Contact'Helper'Data')->getUserEmail()) ?>" class="input-text" type="email" data-validate="{required:true, 'validate-email':true}"/>
            </div>
        </div>
        <div class="field telephone">
            <label class="label" for="telephone"><span><?php /* @escapeNotVerified */ echo __('Phone Number') ?></span></label>
            <div class="control">
                <input name="telephone" id="telephone" title="<?php /* @escapeNotVerified */ echo __('Phone Number') ?>" value="" class="input-text" type="text" />
            </div>
        </div>
        <div class="field comment required">
            <label class="label" for="comment"><span><?php /* @escapeNotVerified */ echo __('What’s on your mind?') ?></span></label>
            <div class="control">
                <textarea name="comment" id="comment" title="<?php /* @escapeNotVerified */ echo __('What’s on your mind?') ?>" class="input-text" cols="5" rows="3" data-validate="{required:true}"></textarea>
            </div>
        </div>
        <?php echo $block->getChildHtml('form.additional.info'); ?>
    </fieldset>
    <div class="actions-toolbar">
        <div class="primary">
            <input type="hidden" name="hideit" id="hideit" value="" />
            <button type="submit" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>" class="action submit primary">
                <span><?php /* @escapeNotVerified */ echo __('Submit') ?></span>
            </button>
        </div>
    </div>
</form>

registration.php

用你自己的VendorName_ModuleName替换。

<?php
'Magento'Framework'Component'ComponentRegistrar::register(
    'Magento'Framework'Component'ComponentRegistrar::MODULE,
    'VendorName_ModuleName',
    __DIR__
);

包含

VendorName_ModuleName替换为您自己的版本,并将0.0.1作为安装版本替换为您自定义模块的版本。

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="VendorName_ModuleName" setup_version="0.0.1" />
</config>

composer.json

当然,如果你想让你的新模块工作,不要忘记添加composer.json

 {
"name": "VendorName/ModuleName",
"autoload": {
    "psr-4": { "VendorName''ModuleName''": "" },
    "files": [ "registration.php" ]
} }

进一步参考
  1. Magento 2 composer.json文档
  2. 在composer中调用registration.php。json with autoload
  3. 在Github上探索Magento的样本模块代码。

您可以使用插件来实现。

首先,您必须重写块并像这样调用beforeToHtml方法:

public function beforeToHtml('Magento'Catalog'Block'Product'View'Description $originalBlock)
{
    $originalBlock->setTemplate('Vendorname_Modulename::description.phtml');
}

我解决了这个问题。如果你想覆盖任何核心文件,你只需使用引用名和这个引用名传递给referenceBlock name="passit"。

对于contactus文件覆盖,首先您获得contactus表单的原始文件。然后找到它的布局文件contact_index_index.xml,并获得引用名称,如"contactForm"

System/core contact_index_index.xml文件

<referenceContainer name="content">
            <block class="Magento'Contact'Block'ContactForm" name="contactForm" template="Magento_Contact::form.phtml">
                <container name="form.additional.info" label="Form Additional Info"/>
            </block>
        </referenceContainer>

这个"contactForm"引用名传递给我们的扩展布局文件在referenceBlock标签。请显示以下代码

我们的扩展布局contact_index_index.xml文件

<referenceBlock name="contactForm">
    <action method="setTemplate">
     <argument name="template"xsi:type="string">Test_Overide::form.phtml</argument>
   </action>
</referenceBlock>

在此之后,系统联系表单。php未调用,我们的扩展表单。php文件调用。

重写核心模板文件最简单的方法:-

module-contact/view/frontend/templates/form.phtml

转到您的主题app/design/frontend/vendor/your_theme/按照以下步骤操作:

  1. 创建Magento_Contact文件夹(将module-contact重命名为Magento-Contact)
  2. 创建模板文件夹
  3. 创建form.phtm或从核心复制form.phtml,然后编辑。

为此您需要创建一个扩展(自定义模块)。

在app/magento中创建block, etcview文件夹

etc文件夹中创建module.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
   <module name="Xyz_Contact" setup_version="0.0.1"></module>
</config>

view文件夹中创建一个layout文件夹,并在名为contact_index_index.xml的文件中放置代码:

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<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>Contact Us</title>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Xyz'Contact'Block'ContactForm" name="contactForm" template="Xyz_Contact::form.phtml">
                <container name="form.additional.info" label="Form Additional Info"/>
            </block>
        </referenceContainer>
    </body>
</page>

创建templates文件夹,并将下面的代码放入form.phtml:

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
// @codingStandardsIgnoreFile
?>
<form class="form contact"
      action="<?php echo $block->getFormAction(); ?>"
      id="contact-form"
      method="post"
      data-hasrequired="<?php echo __('* Required Fields') ?>"
      data-mage-init='{"validation":{}}'>
    <fieldset class="fieldset">
        <legend class="legend"><span><?php echo __('Write Us') ?></span></legend><br />
        <div class="field note no-label"><?php echo __('Jot us a note and we’ll get back to you as quickly as possible.') ?></div>
        <div class="field name required">
            <label class="label" for="name"><span><?php echo __('Name') ?></span></label>
            <div class="control">
                <input name="name" id="name" title="<?php echo __('Name') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento'Contact'Helper'Data')->getUserName()) ?>" class="input-text" type="text" data-validate="{required:true}"/>
            </div>
        </div>
        <div class="field email required">
            <label class="label" for="email"><span><?php echo __('Email') ?></span></label>
            <div class="control">
                <input name="email" id="email" title="<?php echo __('Email') ?>" value="<?php echo $block->escapeHtml($this->helper('Magento'Contact'Helper'Data')->getUserEmail()) ?>" class="input-text" type="email" data-validate="{required:true, 'validate-email':true}"/>
            </div>
        </div>
        <div class="field telephone">
            <label class="label" for="telephone"><span><?php echo __('Phone Number') ?></span></label>
            <div class="control">
                <input name="telephone" id="telephone" title="<?php echo __('Phone Number') ?>" value="" class="input-text" type="text" />
            </div>
        </div>
        <div class="field comment required">
            <label class="label" for="comment"><span><?php echo __('What’s on your mind?') ?></span></label>
            <div class="control">
                <textarea name="comment" id="comment" title="<?php echo __('What’s on your mind?') ?>" class="input-text" cols="5" rows="3" data-validate="{required:true}"></textarea>
            </div>
        </div>
        <?php echo $block->getChildHtml('form.additional.info'); ?>
    </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>

Block文件夹中,创建一个名为ContactForm.php的文件,并使用下面的代码:

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Xyz'Contact'Block;
use Magento'Framework'View'Element'Template;
/**
 * Main contact form block
 */
class ContactForm extends Template
{
    /**
     * @param Template'Context $context
     * @param array $data
     */
    public function __construct(Template'Context $context, array $data = [])
    {
        parent::__construct($context, $data);
        $this->_isScopePrivate = true;
    }
}

请不要忘记在app/etc/config.php中注册您的模块,或者从命令行使用Magento二进制工具:php -f bin/magento module:enable Xyz_Contact .

这里Xyz是公司名称(供应商), Contact是模块名称。

如果你有任何问题请告诉我。