3

I have a service called useTR.php. It has a public method exampleService().

In the variables folder I have added the following code in my KGVariable.php (KG is my plugin name)

public function sayHello() {
    return craft()->useTR->exampleService();
}

In my templates folder I have an html that gets loaded after a form submission and that html has the following code.

<p>Thank you {{ craft.KG.sayHello() }} will contact you soon</p>

When this HTML is loaded, I get the following error:

Twig Runtime Error – Twig_Error_Runtime Calling unknown method: craft\web\twig\variables\CraftVariable::keyword()

What am I doing wrong? Kindly help (I am a beginner at Craft). Thanks.

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
user8983
  • 41
  • 2
  • Do you use Craft 3 or Craft 2. The code is for Craft 2 but the exception for Craft 3. It's likely you are using the wrong code. Furthermore the exception is not really related to your code. You might want to take a look at pluginfactory.io - it creates the entire structure with example code for you – Robin Schambach Nov 04 '18 at 19:44
  • I am using Craft 3. I created the entire structure using pluginfactory.io. Do you see any issue with the way I am writing the code, I mean any obvious issue. – user8983 Nov 05 '18 at 18:15
  • Yes it's for Craft 2 and not Craft 3. There is no craft() function in v3 – Robin Schambach Nov 05 '18 at 18:26

1 Answers1

1

There's a lot going on here, but a) assuming you're really using Craft 3 and b) you generated your plugin, service and variable scaffolding on https://pluginfactory.io, this should work:

KGVariable.php Variable

<?php

namespace kg\variables;

class KGVariable
{
    public function sayHello()
    {
        return \kg\KG::$plugin->useTR->exampleService();
    }
}

UseTR.php Service

<?php

namespace kg\services;

use craft\base\Component;

class UseTR extends Component
{
    public function exampleService()
    {
        $result = 'hello';
        return $result;
    }
}

Then using this in a template will return hello:

{{ craft.kG.sayHello() }}
Brad Bell
  • 67,440
  • 6
  • 73
  • 143