1

I'm trying to call an action from my main class in Craft 3. This is working fine with my services like this:

AbandonedCart::$plugin->serviceExample->serviceMethod();

I've tried to do something similar for my action but it doesn't work and I can't find any solution to it.

AbandonedCart::$plugin->actionExample->actionFunction();

Any ideas on how to do this?

Thanks in advance, Sam

1

You need to call your setComponents function before you are trying to access your components otherwise - logically - they are not defined

public function init()
{
    parent::init();
    self::$plugin = $this;

    // define the components / services
    $this->setComponents(
        [
            'serviceExample' => ServiceExample::class
        ];
    );

    // access them
    $this->serviceExample->serviceMethod();
    // if it's easier for you to remember you can as well use the longer/slower syntax
    AbandonedCart::$plugin->serviceExample->serviceMethod();
);
3
  • Thanks for the tip, this is indeed a better version of what I used. I had to use services\ServiceExample::class to get it working with my services. This however doesn't work for actions in my controller. I get the following error: Missing required parameter "id" when instantiating "abandonedcart\abandonedcart\controllers\DefaultController". – offtheshore Apr 19 '18 at 9:10
  • Why would you even call a controller action in your init function in the first place? That's not intended and bad practice. Controllers are for handling requests and you should route to those actions based on request parameters. – Robin Schambach Apr 19 '18 at 9:19
  • It's for testing an action that'll be triggered by an Ajax request. But I'll test with a service in the mean time. Thanks! – offtheshore Apr 19 '18 at 9:26

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.