I'm, learning magento development and trying to create a custom module in Magento 2.3.6 with page at localhost/magento236/lesson3/Page/view

The template file at Lesson3/Module/view/frontend/templates/homepage.phtml calls ViewModel function to output a friend's name from database

$viewModel = $this->getData('view_model');
$viewModel2 = $block->getViewModel();
echo ($viewModel->getFriendName(1));

ViewModel is located at Lesson3/Module/ViewModel/Lesson3ViewModel.php Part of ViewModel with function to change looks like this

   public function getFriendName($id)
        return $this->getFriendModel($id)->getData('name');

It works fine, shows a name from database with specified ID.

I need to output instead of friend's name any string. So I try to do this with magento plugin interceptor.

Created di.xml at Lesson3/Module/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    <type name="Lesson3\Module\ViewModel\Lesson3ViewModel">
        <plugin name="Lesson3_Module" type="Lesson3\Module\Model\Plugin"
     sortOrder="1" />

Created plugin class at Lesson3/Module/Model/Plugin.php

namespace Lesson3\Module\Model;
class Plugin
    public function aftergetFriendName(
        Lesson3\Module\ViewModel\Lesson3ViewModel $product, $name
    ) {
        $name = "TEXT";
        return $name;

Executed php bin/magento set:di:compile, ran php bin/magento setup:upgrade anf flushed cache php bin/magento cache:flush.

When accessing the page there is Fatal error: Uncaught TypeError: Argument 1 passed to Lesson3\Module\Model\Plugin::aftergetFriendName() must be an instance of Lesson3\Module\Model\Lesson3\Module\ViewModel\Lesson3ViewModel

Please specify to me what should I have done to make it work

  • After run php bin/magento set:di:compile run command, If's there is something permission issue like you do 777 permission on the generated folder then check, I hope it's working! – MOHIT Feb 10 at 17:41
  • I have reset Magento and now I'm getting Fatal error – Fadsa Feb 11 at 8:02

Solved. Should be

 public function aftergetFriendName(
        \Lesson3\Module\ViewModel\Lesson3ViewModel $product, $name


 public function aftergetFriendName(
        Lesson3\Module\ViewModel\Lesson3ViewModel $product, $name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.