2

When providing plugin users with variable containing arguments like {{ craft.pluginname.variable(arg1, arg2) }} what's the best practice for returning something that doesn't throw an Internal Server Error exception for Missing argument 1 or argument 2?

Should this be done as part of the /services/PluginService.php or somewhere else? Is it better to return a nicer Javascript console error (or Craft error log) vs. crashing the page?

2
  • I assume both arg1 and arg2 are required?
    – Brad Bell
    Commented Oct 8, 2014 at 19:40
  • @BradBell - lets say yes. If not set, I'd like to return a nice "no options set" error and an empty output vs. the Internal Server Error crash. Commented Oct 8, 2014 at 19:42

2 Answers 2

6

I think the best way to do this would be in your PluginHandleVariable file's method, just have it accept one, optional parameter and expect it to be an array.

public function variableMethod($options = null)
{
    if (!$options || !is_array($options))
    {
        return "No options set";
    }

    // Now you can check for individual options on the array
    if (isset($options['option1'])
    {
        ....
    }

}

Then both of these would work:

if craft.pluginname.variable()
if craft.pluginname.variable(options)
0
1

You can use the is defined twig expression to determine if a variable is defined or not. Something like this:

{% if craft.pluginname.variable(arg1, arg2) is defined %}
    {{ craft.pluginname.variable(arg1, arg2) }}
{% elseif %}
    <p class="notice">Display notice.</p>.
{% endif %}
2
  • 1
    Sorry. I wrote this before reading the comments above. Commented Oct 8, 2014 at 19:46
  • This is good but I'd like it to be self contained within the plugin so you would only need to include {{ craft.pluginname.variable(arg1, arg2) }} Commented Oct 8, 2014 at 19:47

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.