We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Adding data to a Model object on-the-fly and sending to the View

Phalcon's ResultSet is great, only storing one record in memory at a time, but it's causing me real headaches trying to add custom data to an object after it's been pulled from the database.

My indexAction() looks like so:

$webm = new MyModel();
$visas = $webm->customFindFunction($variable);
foreach ($visas as $visa) {
   $randomVar = $webm->otherFindFunction($visa->id);
   $visa->newParam = $randomVar;
}
$this->view->visas = $visas;

However, because newParam is not part of the Model and because the object is not saved between rows, by the time it's pushed to the view, it's lost (removed from memory and not saved). Is there any way around this? newParam is literally only needed on the View...

If I print_r() within the for loop I can see my newParam being assigned, but if I print_r() after it has ended, it's gone again.

It might help a bit to know what you're actually trying to accomplish - it looks like this is just an illustration, but I still have questions as to why you're wanting to do this.

The reason print_r() within the loop works is because $visa is still a reference to the object you affected. You're not re-assigning $visa back into $visas. You could try doing a foreach by reference:

foreach($visas as &$visa)

But references like that can be troublesome: https://schlueters.de/blog/archives/141-references-and-foreach.html. Still, if this is all you're doing, and you're not iterating through $visas again, or using $visa as another variable, it should be safe.

Is $randomVar a property that's related to each $visa? If so, might you be able to set up a relationship, then just reference that relationship from the view? I would recommend this method if possible.

It's not about reference, by default all php objects are passed as reference.

You basically CAN'T modify resultset in anyway in phalcon.

This part of code:

foreach ($visas as $visa) {

}

Is just getting each row as current row and you can do some stuff with it, but there is no way to save it anyhow to $visas. This is how phalcon resultset works and why it's really fast.

If you want to modify it, then use toArray() method on resultset, and work on arrays with reference.