Why I'm getting Uncaught TypeError when creating a Magento 2 plugin?
-
09-10-2020 - |
Question
I was trying to create a plugin for existing Magento 2 extension, but it is always getting Uncaught TypeError:
Fatal Error: 'Uncaught TypeError: Argument 1 passed to
Vinc\discount4customer\Plugin\CheckoutCouponApply::__construct() must
be an instance of Vinc\discount4customer\Model\AccountFactory,
instance of Magento\Framework\ObjectManager\ObjectManager given,
called in
/var/www/m2site/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php
on line 93 and defined in
/var/www/m2site/app/code/Vinc/discount4customer/Plugin/CheckoutCouponApply.php:30
Stack trace:
#0 /var/www/m2site/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(93):
Vinc\discount4customer\Plugin\CheckoutCouponApply-__construct(Object(Magento\Framework\ObjectManager\ObjectManager))
#1 /var/www/m2site/vendor/magento/framework/ObjectManager/Factory/Compiled.php(88):
Magento\Framework\ObjectManager\Factory\AbstractFactory-createObject('Vinc\\discou...',
Array)
#2 /var/www/m2site/vendor/magento/framework/ObjectManager/ObjectManager.php(71):
Magento\Framework\ObjectManager\Factory\Compiled-create('Vinc\\discou...')'
in
'/var/www/m2site/app/code/Vinc/discount4customer/Plugin/CheckoutCouponApply.php'
on line 30";root@vs:/home/uuii/websites/m2site/var/report/api#**
My plugin page is very simple as following:
It came from There is an event or method to “plug-in” when the coupon is removed from the cart/quote in the checkout flow?
<?php
namespace Vinc\discount4customer\Plugin;
use Magento\Quote\Model\CouponManagement as CouponManagement;
use Vinc\discount4customer\Model\AccountFactory;
//use Magento\Framework\Event\ObserverInterface;
class CheckoutCouponApply {
protected $accountFactory;
public function __construct(
AccountFactory $accountFactory
)
{
$this->accountFactory = $accountFactory;
}
public function beforeSet(CouponManagement $subject, $cartId, $couponCode)
{
$account = $this->accountFactory->create()->loadByCode($couponCode);
// Do what you need to do
file_put_contents("/var/www/m2site/var/log/c".time().".txt",$couponCode ."--" .date("Y-m-d H:i:s").$account);
}
}
?>
it seems I couldn't use the functions under another namespace? thanks advance for helping.
Solution
For factory to be created Vinc\discount4customer\Model\Account must exist. This error can also occur if you have done argument replacement using in di.xml. can you make sure that there is nothing like this in your di.xml and the class exists. You should also be in able to see your factory generated in var/generation
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange