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?

  • I assume both arg1 and arg2 are required? – Brad Bell Oct 8 '14 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. – Adam McCombs Oct 8 '14 at 19:42
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)
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 %}
  • 1
    Sorry. I wrote this before reading the comments above. – Douglas McDonald Oct 8 '14 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) }} – Adam McCombs Oct 8 '14 at 19:47

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.