XF 2.1 Add custom key-value pair after finder fetch()?

asprin

Active member
Hi,

After using the following code:
PHP:
$repo = $this->repository('FC:Events');
$finder = $repo->fetchAllEvents()->limitByPage($page, $perPage);
$events = $finder->fetch();
echo '<pre>';
print_r($events);
echo '</pre>';
The output is as follows:
1580290137010.webp

Can I add some custom values to this entity apart from the ones already present? For example, after event_status, I would want to have [foo] => 'bar'

Is this a possibility?
 
I think getters are what will serve my purpose. In my Entity controller, I've the following:
PHP:
$structure->getters = ['foo' => true];

public function getFoo()
{
    return 10;
}

This is working and I'm getting back "10" by accessing the $obj->foo in the template. However, is it possible to access the primary key value inside getFoo() so that I can return a dynamic value instead of a hard-coded value. I hope I'm making sense.

For example:
Code:
$events = $finder->fetch();
foreach($events as $event)
{
    echo $event->foo; // is it possible to pass the event_id to the getFoo function
}

Use case is to use the event_id inside getFoo() to do SELECT query on another table and get some additional data returned.
 
Last edited:
As the getter is part of the entity, you could access it (as well as any other columns/relations/getters) inside the getter method via $this->event_id.
 
Works like a charm! A bit silly that I never thought of trying that out 🤦‍♂️

On a side note, would you be so kind to explain the difference between the following?

PHP:
$structure->getters = ['foo' => true]; // what does it mean when set to true

$structure->getters = ['foo' => false]; // similary false implies what

$structure->getters = ['foo' => "some_value"]; // is this supported? if so what does it imply?
 
The true/false values are a short-hand for whether or not the values should be cached (if cached, the method will not be run on subsequent accesses of the getter).

Alternatively, you can specify the value as an array if you want to specify the getter method explicitly:
PHP:
'foo' => [
    'getter' => 'doSomething',
    'cache' => false,
];

If you do this, cache is true by default if omitted.
 
Hmm...not sure why I do not have the option of editing the thread title to indicate that a solution was provided. I guess it's time bound after which edit option is removed.
 
Back
Top Bottom