1

What is the best practice for defining an attribute on an Entry that isn't persistent? For example, I want to create a formatted string from two separate values stored in fields on the entry, but don't need to store the computed value in a field or in the database.

I realize I can do this in a template variable like so:

{% set fullName = entry.firstName ~ " " ~ entry.lastName %}

... but, it would be much better if I could define this in a more global way so it can be used any time I'm dealing with an Entry within a specific Section like so:

{{ entry.fullName }}

I've read about custom Modules but that seems like overkill. Also, Craft may not offer any API to do something like this, but Yii might?

Halp.

1

You can use behaviors to add new methods to system components. See the link above for documentation. A behavior is a class that extends yii\base\Behavior and is attached to a component using the EVENT_DEFINE_BEHAVIORS event.

First you define the class that provides your custom method:

use yii\base\Behavior;

class FullNameBehavior extends Behavior {
    public function fullName() {
        return "{$this->owner->firstName} {$this->owner->lastName}";
    }
}

The attach that behavior to the Entry class:

use craft\elements\Entry;
use craft\events\DefineBehaviorsEvent;
use yii\base\Event;

// init() method in a module
Event::on(
    Entry::class,
    Entry::EVENT_DEFINE_BEHAVIORS,
    function (DefineBehaviorsEvent $e) {
        $e->sender->attachBehaviors([
            FullNameBehavior::class,
        ]);
    }
);

Now you can use the method in Twig:

{{ entry.fullName }}

You can put the behavior class and the event hook in a module.

Alternative approaches

I don't really like behaviors in general, as it's very hard to find out where their methods are defined if you don't know about them. Also, tacking endless additional methods onto a class that doesn't really have anything to do with them is kind of bad design.

Instead, consider the following solutions:

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.