简体   繁体   English

在Magento 2中如何覆盖phtml或布局核心文件?

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

I had developed "Hello world" extension in Magento 2. 我在Magento 2中开发了“Hello world”扩展。

I want to override contact Us form of core files. 我想覆盖联系我们的核心文件形式。 What is correct way for overriding Contact us form file in Magento 2. 什么是覆盖的正确方法在Magento 2中联系我们表单文件。

Please help me. 请帮我。 Any help would be appreciated. 任何帮助,将不胜感激。

Unlike the two previous answers, I chose to remove the original block from the layout and add a new one using my own template . 与之前的两个答案不同,我选择从布局中删除原始块 ,并使用我自己的模板添加一个新

We will create a new module, VendorName_ModuleName , for which we need to create the following files : 我们将创建一个新模块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

Every module in Magento 2 has unique name that's made up of two parts. Magento 2中的每个模块都有唯一的名称,由两部分组成。 The first part is a word that describes the company, individual, or group that built the extension. 第一部分是描述构建扩展的公司,个人或团体的词。 This is sometimes called the “ vendor ” namespace. 这有时称为“ 供应商 ”命名空间。 The second part of a module ’s name is a word that describes what the module does. 模块名称的第二部分是描述模块功能的单词。

Alan Storm , in his tutorial Magento 2 Hello World Module Alan Storm ,在他的教程Magento 2 Hello World Module中


contact_index_index.xml 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>

In the above code, I removed the original form Block and replaced it by adding my own form inside the referenceContainer content. 在上面的代码中,我删除了原始表单Block并通过在referenceContainer内容中添加我自己的表单来替换它。

Note : 注意 :

In contact_index_index.xml , the code template="My_Module::form.phtml" refers to your custom contact form's phtml . contact_index_index.xml ,代码template="My_Module::form.phtml"是指您的自定义联系表单的phtml


form.phtml form.phtml

Now, you need to make the custom form template. 现在,您需要制作自定义表单模板。 You can copy the original one and make modifications to this file. 您可以复制原始文件并对此文件进行修改。

<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 为registration.php

Simply replace the VendorName_ModuleName with your own. 只需将VendorName_ModuleName替换为您自己的。

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

module.xml module.xml

Replace VendorName_ModuleName with your own and 0.0.1 as setup version with the version of your custom module. 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

Of course, if you want to make your new module work, don't forget to add composer.json . 当然,如果您想让新模块工作,请不要忘记添加composer.json

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

Further Reference 进一步参考

  1. Magento 2 documentation for composer.json composer.json的 Magento 2文档
  2. Invoke registration.php in composer.json with autoload 使用autoload在composer.json中调用registration.php
  3. Explore the code of Sample Modules by Magento on Github . 在Github上探索MagentoSample Modules代码。

You can do it using a plugin. 你可以使用插件来做到这一点。

First you have to override the block and call the beforeToHtml method like this: 首先,你必须覆盖块并调用beforeToHtml方法,如下所示:

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

i solved this problem. 我解决了这个问题。 if you want to override any core files, you simply use reference name and this reference name passed to referenceBlock name="passit". 如果要覆盖任何核心文件,只需使用引用名称,并将此引用名称传递给referenceBlock name =“passit”。

For conatct us file override, first you get the original file of contactus form.phtml and after that find it's layout file contact_index_index.xml and get the reference name like "contactForm" . 对于conatct us file override,首先获取contactus form.phtml的原始文件,然后找到它的布局文件contact_index_index.xml并获取类似“contactForm”的引用名称。

System/core contact_index_index.xml File. 系统/核心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>

This "contactForm" reference name passed to our extension layout file in referenceBlock tag. 这个“contactForm”引用名称传递给referenceBlock标记中的扩展布局文件。 Please show following code. 请显示以下代码。

Our Extension layout contact_index_index.xml file 我们的扩展布局contact_index_index.xml文件

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

After this , system contactus form.phtml not called, Our extension form.phtml file called. 在此之后,系统contactus form.phtml没有调用,我们的扩展名是form.phtml文件。 You can check using Developer front end debugging tool. 您可以使用Developer前端调试工具进行检查。

Hi easiest way to override core template file:- 最简单的方法来覆盖核心模板文件: -

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

go to your theme app/design/frontend/vendor/your_theme/ follow below steps: 转到您的主题app/design/frontend/vendor/your_theme/按照以下步骤操作:

  1. Create Magento_Contact folder (Renamed module-contact to Magento-Contact) 创建Magento_Contact文件夹(重命名模块 - 联系到Magento-Contact)
  2. Create templates folder 创建模板文件夹
  3. Create form.phtm or copy your form.phtml from core and then edit it. 创建form.phtm或从core中复制form.phtml然后进行编辑。

For this you need to create an extension (custom module). 为此,您需要创建一个扩展(自定义模块)。

Create a block , etc and view folder from app/magento. 创建一个block etc并从app / magento view文件夹。

In the etc folder create module.xml : 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>

In the view folder create a layout folder and place code below in a file named contact_index_index.xml : 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>

Create templates folder and place the code below into form.phtml : 创建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>

In Block folder, create a file named ContactForm.php and use the code below: 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;
    }
}

Please do not forget to register your module in app/etc/config.php , or using the Magento binary tool from the command line: php -f bin/magento module:enable Xyz_Contact . 请不要忘记在app/etc/config.php注册模块,或者从命令行使用Magento二进制工具: php -f bin/magento module:enable Xyz_Contact

Here Xyz is the name of company (the vendor ) and Contact is the module name. 这里Xyz是公司名称( 供应商 ), Contact是模块名称。

Let me know if you have any questions. 如果您有任何疑问,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM