2

I have a plugin called "myPlugin", this has a variables file. Within there, I have a something like this:

public function helloWorld() { return "Hello World"; }

Also within this plugin, I've created a new fieldtype. From the "getInputHtml" function, I'd like to call the "helloWorld()" function.

How can I do this? This was my initial trail of thought:

$testing = craft()->myPlugin->helloWorld();

or

$testing = craft()->myPlugin->myPluginVariable->helloWorld();

1 Answer 1

4

From what I understand about plugin development on Craft, this isn’t possible. The idea of the variables file is to provide methods which are accessible from within your plugin or users templates.

The idea being that the methods you define here are actually references to your service methods (Taken from Craft docs)

Many of your template variable methods will likely be simple wrappers for your service API methods. It’s important to remember not to expose state-changing methods, however.

So from that I would actually create a service class for your plugin and access the methods in your getInputHtml function from that.

For example:

services/MyPlugin_PluginService.php

<?php
namespace Craft;

class MyPlugin_PluginService extends BaseApplicationComponent
{
 public function helloWorld()
 {
   return ‘Hello World’;    
  }
}

In your getInputHtml function

$testing = craft()->myPlugin_plugin->helloWorld();

Call the same method in your templates

Add this to your variables/MyPluginVariable.php file to call the method in your templates:

public function sayHello() {
  return craft()->myPlugin_plugin->helloWorld();
}

Then you could call the service method in your templates like so:

{{ craft.myPlugin.sayHello() }}

Hope that helps!

2
  • This works perfectly, thank you Alec! I'm still trying to familiarize myself with the way plugins are structured, and this is just another scenario where I overlook areas I shouldn't be. The idea was to have a function that sits somewhere, which I can call from the frontend AND from within a plugin. Wonder if I can call the service plugin from the frontend too? {{ craft.myPlugin_plugin.helloWorld() }}. Will look into it properly this afternoon. Thanks again. Commented Oct 21, 2014 at 14:01
  • No worries, it took me a while to get my head around it to. I've updated my answer to show how you would call the same method in your templates :) Commented Oct 21, 2014 at 15:10

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.