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

edit model::find(); results in an foreach loop

As https://docs.phalcon.io/en/latest/reference/models.html#understanding-records-to-objects says, you can edit the objects once its loaded in the memory.

    $settingCategories = SettingCategory::find();
    $this->view->setVar("settingCategories",$settingCategories);
    foreach($settingCategories as $settingCategory){
        if($settingCategory->type == "2"){
            $settingCategory->type = "asd";
            $settingCategory->intersection = "asd";
        }else{
            $settingCategory->type = "blaa";
            $settingCategory->intersection = "blaa";
        }
        $settingCategory->type = "test";
    }

type is still its default value when I loop through it with volt:

{% for settingCategory in settingCategories %}
<div class="tab-content">
    <h4>{{ settingCategory.name }}</h4> 
    <h4>{{ settingCategory.type }}</h4> --> still (int) integer!?
    <h4>{{ settingCategory.intersection }}</h4> --> undefined
</div>
{% endfor %}


43.9k

you have set the view variable "settingCategories" in the controller after datas are fetched, so naturally, when looping trough it in the view, it will use these "raw" values ...

I did that thank you!

but still the same results



8.7k

Have you forgotten to use $settingCategory->save(); at the end of every loop?



8.7k

Also, you need to add

$this->view->setVar("settingCategories",$settingCategories);

After the foreach loop not before it. You are simply assignning the old values, even before you change them..

I don't want to save it to the database, it is for passing to the view only. so ->save(); is not needed.

And I added setVar at the end

my code:

    $settingCategories = SettingCategory::find();
    foreach($settingCategories as $settingCategory){
        if($settingCategory->type == "2"){
            $settingCategory->type = "asd";
            $settingCategory->intersection = "asd";
        }else{
            $settingCategory->type = "blaa";
            $settingCategory->intersection = "blaa";
        }
        $settingCategory->pages = "test";
    }
    $this->view->setVar("settingCategories",$settingCategories);

Can you try it yourself? Loop through results and change values, and then pass is to the view.



8.7k
Accepted
answer

Sorry, I'm out of my desk.

Use - >toArray() on each of these, do your modifications and add them to a new array, then pass it to the view.

Regards

Thank you! It works!



8.7k

You are welcome. Don't forget to give me some points.

I did, didn't I?

Otherwise tell me how