0

I want to send a value from a controller to a view on each iteration of a foreach loop.

Context:

I have an array that has 100 elements as an example. In the controller, I want to loop the array and for each iteration send a value to the view. How can I do that in Symfony

Here is the code example

$myArray = ["val1", "val2", "val100"];
foreach ($myArray as $key => $val) {
   // here I want to send the data (val1 to val100) to the view on each iteration
}

Note:

With return this->json(...) or new JsonResponse(...), in the loop, the loop stops after the first iteration. If you put it outside of the loop, only the last val (val100 in this example) is rendered.

Why do I want to do that?

Let's say I am working on a symfony project to insert data into a database from excel file or something similar. After reading the file in the controller, I'm inserting the data one by one into the related table via a foreach loop and I aslo want to feed a progress bar which is in the view to let the user know that data is inserting like (1/100, 2/100 ... 100/100). How can I pass the data on each iteration from the loop to reach the view.

Data is inserted into the db successfully, but I still can't find a way to feed the progress bar in the view on each iteration of the loop

In advance, many thanks.

EE2017
  • 49
  • 11
  • Instead of trying to do this inside the controller all at once, it will be more simple to separate the actions in a queue and process the queue with ajax calls – DarkBee May 09 '22 at 09:22
  • @DarkBee That way, will the progress bar be fed after the insertion into the db or while data is being inserted into the db table? – EE2017 May 09 '22 at 10:02
  • 1
    This will be during, create a queue and execute each task one by one. This way you'll have full controll over the progress - [See here](https://stackoverflow.com/questions/57554076/run-ajax-request-one-by-one-on-whole-table) – DarkBee May 09 '22 at 10:17
  • @DarkBee Thanks, I will try to understand that code... – EE2017 May 09 '22 at 12:51

0 Answers0