D
D
Dmitry2016-12-20 20:50:56
Yii
Dmitry, 2016-12-20 20:50:56

How to correctly implement the form of adding n-copies of the same model (inputs) in one form without reloading?

Good day.
There is a form for creating an indefinite number of products.
Model - Product.
How to properly compose this form so that you can create an unlimited number of products (array)?
If I need to duplicate a field, then I do this:

<input type="text" name="Product[field_name][]">
<input type="text" name="Product[field_name][]">

But how to do this, but for the whole model?
There were ideas and even the implementation of a random key substitution according to a template, on the fly using JS, but I feel that this is a very rough crutch, which else I need to look for.
Ideally, I would like an entry like:
<input type="text" name="Product[][name]">
<input type="text" name="Product[][description]">

worked by analogy with the previous version, but, alas, this is not realistic.
Maybe there is a way to similarly define fields within a tag?
Like:
<!-- Первый продукт, запишется с ключом 0 -->
<form-item>
    <input type="text" name="Product[][name]">
    <input type="text" name="Product[][description]">
</form-item>
<!-- Второй продукт, запишется с ключом 1 -->
<form-item>
    <input type="text" name="Product[][name]">
    <input type="text" name="Product[][description]">
</form-item>

You can, of course, when creating a new form instance, send it not from a hidden template on the page, but through AJAX loading, where on the PHP side, in the action, create a new model for this form, save, get the ID of the created model and use this ID as a key .
However, if there is no more elegant solution, getting the form's HTML code via AJAX is the most acceptable option.
Thanks in advance for any replies.
UPD:
It is not forms that multiply, but models that need to be filled out. And their number is dynamically changing. Therefore, in my case, it is optimal to use the model ID as a key:
<input type="text" name="Product[<?=$productModel->id;?>][name]">
<input type="text" name="Product[<?=$productModel->id;?>][description]">

That is, request the form via AJAX and, when rendering the form, specify the key of the new model created upon request, which is already stored in the database under the incremented ID.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2016-12-20
@slo_nik

Good evening.
If I understood you correctly, then we are talking about "Table entry"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question