1

How to make a plugin for a model and turn one of its fields into a different value.

For example, in the documentation, they make an after plugin for the model and return a different value.

    public function afterGetName(\Magento\Catalog\Model\Product $subject, $result)
    {
        return '|' . $result . '|';
    }

How to do the same only through around?

My modules do not have get name methods and the like. I have a standard Model, I load it through Factory in my class and create a method to get all data from modules using:

    public function getAllMyData()
    {
        return $this->friendFactory->create()->getCollection();
    }

and use plugin

    public function aroundGetAllMyData(\My\Module\ViewModel\MyViewOnModel $subject, callable $proceed)
    {
        return $subject;
    }

1 Answer 1

0

No need for a plugin to modify your model data, if you own the model

In your Model Class, lets assume

\Vendor\Module\Model\Friend

You have a field in the collection nickname and you want to change the nickname to some text or append some text to the existing nick name, when you load and retrieve the collection

So, just throw a getter method getNickname

public function getNickname() {
    return ' My Besty';
}

In case if you want to append some thing to the existing data then you can use this,

public function getNickname() {
    return parent::getNickname() . ' My Besty';
}

If you retrieve your collection, and getNickname() you can find the changed or appended string.

BTW you can also add a different method like getNicknameWithBesty and retrieve the data.

public function getNicknameWithBesty() {
    return parent::getNickname() . ' My Besty';
}

Your Answer

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

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