Dan Abramov
Dan Abramov

Reputation: 268265

Should I use one form on page or generate a form per item?

I want to display a list of items. Each item would have an edit and a delete icon next to it.

For obvious reasons I want to trigger the delete action with HTTP POST.
With jQuery, I would bind links to trigger form.submit.

However I'm not sure if I should generate a form next to each item or use just one form.
Below are pros and cons of two approaches as I see them.

Form Per Item:

Single Form:

What is there to add? What is the preferred pattern in modern HTML apps?

Upvotes: 1

Views: 133

Answers (3)

Dan Abramov
Dan Abramov

Reputation: 268265

In the end, I decided to go with AJAX via jQuery.ajax.

The reason is semantically I don't even have forms—I have buttons.
Therefore, jQuery is an easier solution as it allows to keep posting logic in one place (as opposed to scattering it across HTML and JS).

I assigned row class to each semantical row and put corresponding database IDs in HTML5 data attribute called data-row-id for each row.

<div class="row" data-item-id="{{ product.id }}">
    <!-- ... --->

    <a href="#" class="delete-btn"><img src="/img/delete.png" alt="Delete"></a>
</div>

Then I have something alone the lines of

$('.delete-btn').click(function() {
    var row = $(this).closest('.row');
    var id = row.data('item-id');

    $.ajax({
        url: id + '/delete/',
        type: 'POST'
    });

    row.fadeOut().slideUp();
    return false;
}

in my $() load handler.

This solution scales beautifully across the whole codebase because you only have to set row class and data-item-id attribute and the buttons will “just work”.

Upvotes: 0

Xavi L&#243;pez
Xavi L&#243;pez

Reputation: 27880

The main disadvantage I see in having a single form enclosing all list elements is that you can end up with a huge POST if the list is long. As an advantage, you could mark multiple elements for deletion (checkboxes, for instance) and perform a single delete request.

I'd go for either

  1. A single form for each list element. This would make deletion of multiple elements impossible, but would keep POST sizes minimal.
  2. Using a single form, but in a way that doesn't include all the list elements. For instance, having a delete only form with a single hidden element in it, into which you would put all the id's marked for deletion with JS manipulation.

As a side note, you could also skip forms and perform the needed interactions through ajax. This would improve user experience notably. Take into account that forms would still be needed to provide fallback mechanisms in case it was required.

Upvotes: 1

Kalessin
Kalessin

Reputation: 2302

I have used checkboxes in the past. This is better for usability, and each checked checkbox can pass its own ID to the form processing script.

Upvotes: 1

Related Questions