Search code examples
twigsymfony4

How can I fill the object of a class with data that come from loop?


How can I fill the object of a class with data that come from loop?

My apologies if I explain the problem with wrong terms..

I need my object to be filled with the numbers I recover from twig's form. Then, I want this object to be persisted and flushed. As simple as that.

I do not understand how can I fill my object because the numbers I recover from twig are inside the loop which is inside the table.

Thank you in advance for all possible ideas..

Here is my twig :

<form name="order" action="{{ path('edit_book',{'id_book':id_book}) }}" 
method="post">
<table >
{%  for d in pages %}
    <tbody>

    <tr>

        <td>
{{ d.title }}
        </td>


        <td>
             <input name="order_{{ d.idPage }}" size="3" id="{{ d.idPage 
}}" value="{{ d.order }}">
        </td>

    </tr>

{%  endif %}
    </tbody>
{% endfor %}
    <tfoot>
    <tr>

        <td align="right" colspan="3" style="width: 45px;">
            <div style="float: right;">
                    <input type="submit" name="commit" title="Order">
            </div>
        </td>
    </tr>

    </tfoot>
</table>
</form>

My Controller:

/**
 * @Route("/book/edit/id_site/{id_book}", name="edit_book")
 */
public function edit(Request $request, $id_book)
{

    $value=$_POST;
    dump($value); 

    $order = new Page();

    $order->setIdSite($id_book);
    $order->setOrder($value['order_{{ d.idPage }}']);  // this, of course, does not work...

    dump($order); /*die;*/

Solution

  • First u'd need to rename your input so you can math the ID with the order, e.g.

    <input name="order[{{ d.idPage }}]" size="3" id="page_{{ d.idPage }}" value="{{ d.order }}">
    

    The input order is now an array, which you can loop in PHP:

    foreach($_POST['order'] as $page_id => $order) {
        $order = new Page(); // <--- you prolly want to fetch an existing page here with $page_id
        $order->setIdSite($id_book);
        $order->setOrder($order);  // this, of course, does not work...
        dump($order); /*die;*/
    }