1

I want to override a class in a composer installed vendor package on Magento 2.

Firstly I have a child theme of the default theme Luma. Secondly I installed the vendor package via composer.

I have two questions.

  1. Can I put my code in app/design/frontend/Myvendor/mytheme/<Vendorname_vendormodule>/ or do I need to put it in app/code/
  2. How can I override this specific class only, which is vendor/<vendorname>/module-<vendormodule>/Block/Product/Info.php ?
asked Mar 10, 2019 at 13:08
1
  • I would suggest you override it using custom module in app/code Commented Mar 10, 2019 at 13:32

1 Answer 1

0

For your first question : It depends which code you want to override.

  • For example you want to change the theme,the layout and front end display (not any functional change) you can do it.app/design/frontend/Myvendor/mytheme/<Vendorname_vendormodule>/

  • If you want to update/rewrite the logic you have to do it in app/code/{Vendor}/{Module}.


For your second question : To override block you need to add code in app/code/{Vendor}/{Module} directory by following steps

For example you have to override Magento\Catalog\Block\Product\ListProduct block

1.) create file app/code/{Vendor}/{Module}/etc/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">
 <preference for="Magento\Catalog\Block\Product\ListProduct" type="{Vendor}\{Module}\Block\Rewrite\Product\ListProduct" />
</config>

2.) create file app/code/{Vendor}/{Module}/Block/Rewrite/Product/ListProduct.php

<?php
 /**
 * Hello Rewrite Product ListProduct Block
 */
 namespace {Vendor}\{Module}\Block\Rewrite\Product;
 class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
 {
 public function _getProductCollection()
 {
 // Do your stuff here
 }
 }

Ref: Overriding Block, Model, Controller in Magento2

answered Mar 10, 2019 at 13:56
1
  • Does not work for me sadly. Nothing happens. Commented Mar 11, 2019 at 16:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.