简体   繁体   中英

KnockoutJS + Symfony2 + Twig collection form add and remove items

I am trying to implement Knockout into my Symfony2 projects and I've come to a point where I need to integrate a collectiontype into my form. I have followed Symfony2 documentation ( http://symfony.com/doc/current/reference/forms/types/collection.html ). I have plenty of experience in SF2. However, I am recently starting on Knockout.

What I would like to know is how can I combine the symfony2's twig {% for bform in form.a.bs %} with the data-bind="foreach: b" so that my table displays the current data and also lets me add/remove using KnockoutJS.

I still don't have a working piece of code because I am thinking how can I achieve this but this is an example of the <tbody> of the table:

<tbody data-prototype="{{ form_widget(form.a.bs.vars.prototype)|e }}">
{% for bForm in form.a.bs %}
<tr>
    <td>{{ form_widget(bForm.first) }}</td>
    <td>{{ form_widget(bForm.second) }}</td>       
</tr>
{% endfor %}
</tbody>

In my Knockout I currently have:

function viewModel() {
    self = this;
    self.bs = ko.observableArray();
    self.addB = function() {
        // Logic to add a new form row in the table provided in SF2 documentation above
    }
}
ko.applyBindings(new viewModel());

I don't know how to proceed in order to wrap this together. I am aware that I can use JSON with Knockout but thinking it from a SF2 perspective, when you hit an action lets say createAAction() {} that returns the .html.twig with the form, All I see in the Knockout documentation is how to retrieve JSON from the server but that's not really my case. I would like for when the page loads with the current information, knockout picks it up.

Let me know if this isn't clear enough.

There's not going to be any straightforward or worthwhile way to make that work with Knockout. The whole premise of Knockout is that all data is in the viewmodel, and the view reflects the viewmodel and accepts input for the viewmodel. Symphony2 puts the data in the view.

You will do better to use jQuery to perform the DOM manipulations you want to do.

You can certainly use Knockout's observables and computeds behind the scenes if that helps you manage your data dependencies, and you could even put some bindings on the page as long as they are in pieces of the DOM that will not be managed by anything else . But combining Knockout bindings with another DOM-constructing system will not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM