Welcome Guest, Not a member yet? Register   Sign In
function requires loop data
#1

[eluser]Unknown[/eluser]
Hello,

How can I pass a functions data into a view if it requires the table data in the views foreach loop.

e.g view_index.php

Code:
foreach ($posts as $post) {
if (has_subscribed($post->id)) {
echo "has subscribed";
}
}

The has_subscribed function is querying the database using the post->id and returning true/false.

Now obviously I can't place that function in my view?
So how do I pass that data from my controller to my view?
#2

[eluser]rana[/eluser]
First thing, its not like "you can't place the function in view" , but more likely, you shouldn't to keep the MVC model meaningful. From your code examples, it seems that, you could do this 'subscribed' value retrieved while retrieving the 'posts' data by doing some join operation, and it is strongly recommended. For another alternative, you can make another loop inside controller/libraries/models to loop through the posts and have the proper flag assigned like:

Code:
foreach($posts as $post){
   $post->subscribed = has_subscribed($post->id);
}
But it is going to give you an extra loop computation. So, you should be careful and consider the amoung of database data to be shown on page before implementation in such way.
#3

[eluser]Unknown[/eluser]
Hello you mentioned adding another loop in my model/controller but how can I do this when my main foreach loop is in the view? How do I get the $post->id into my controller/model?
#4

[eluser]TheFuzzy0ne[/eluser]
I think what rana means, is that you would process your data first in the model, and then loop over it again in your view. Generally, your model should pass data back in the format you need it in with any data you need included.

Personally, I don't see why you can't just join both of your tables together. And then just loop through them once. With the right query, you should be able to get all the data you need in a single query. If you could post your table structures, I might be able to give you an example.




Theme © iAndrew 2016 - Forum software by © MyBB