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.

  • 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 4 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 5 at 18:15
  • Yes it's for Craft 2 and not Craft 3. There is no craft() function in v3 – Robin Schambach Nov 5 at 18:26

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() }}
  • It gives me the following error: – user8983 Nov 6 at 3:43
  • Calling unknown method: craft\web\twig\variables\CraftVariable::keyword() – user8983 Nov 6 at 3:49
  • You've got something going on somewhere else, then. The string keyword isn't in any of the code posted above or generated by pluginfactory.io. – Brad Bell Nov 6 at 19:52

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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