2

I have a model with the following functions:

public function render() 
{
    $render = craft()->templates->render('myplugin/templates/mymodeltemplate');
    return $render;
}

public function __toString()
{
    return $this->render();
}

Calling __toString() gives me the following error:

Fatal error: Method Craft\MyModel::__toString() must not throw an exception in /projectpath/craft/app/vendor/twig/twig/lib/Twig/Extension/Core.php on line 0

I've found this explanation:

http://php.net/manual/en/migration52.incompatible.php

But I'm not sure how to work around it and accomplish what I'm trying to do...

3

In PHP, nothing can throw an exception inside of a __toString() method, or else you'll get the error you're seeing.

Not only is that a questionable design decision, it also hides the underlying exception message and stack trace from you.

If you do this, at least you'll be able to log the underlying error and fix that:

public function __toString()
{
    try
    {
        return $this->render();
    }
    catch (\Exception $e)
    {
        Craft::log('ERROR: '.$e->getMessage(), LogLevel::Error);
    }
}

Then you can look in your craft/storage/runtime/logs files for [error] to see the exception message.

  • Thanks! The error log revealed a path issue in how I was calling my template. I needed to do this: $oldpath = craft()->path->getTemplatesPath(); $newpath = craft()->path->getPluginsPath().'myplugin/templates/'; $render = craft()->templates->render('mymodeltemplate'); Though the html string returned renders in the browser with html entities encoded. HTML entities still appear when passing the string through html_entity_decode() before returning the result in the __toString() function. Which leaves me curious about what is happening between the Model and the template rendering engine. – Angela T Oct 8 '14 at 18:22
  • @AngelaT Hey Angela, I’ve edited your question to just focus on the PHP error you were getting. Can you post your previous comment as an answer to the question, and then mark it as the accepted answer? I’ll answer the template escaping question in your new post. – Brandon Kelly Oct 9 '14 at 15:47
1

At Brad's suggestion, the error log revealed a path issue in how I was calling my template. I needed to do this:

$oldpath = craft()->path->getTemplatesPath(); $newpath = craft()->path->getPluginsPath().'myplugin/templates/'; $render = craft()->templates->render('mymodeltemplate');

Though the html string returned renders in the browser with html entities encoded. HTML entities still appear when passing the string through html_entity_decode() before returning the result in the __toString() function. Brandon addresses that issue here.

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.