Nikola Loncar
Nikola Loncar

Reputation: 2671

Table sheet like data in symfony2 form

I need to have this type of data in my form :

value11, value12, value13 ...
value21, value22, value23
value31, value32, value33 
value41, value42, value43
...

This is how the form should look like :

form design

Is there any form type that can do that automatically or the form must be created manually? There is collection type but its seems cant fit in my case. I am planing to serialize data from this table sheet and story it to single db table column (single property of entity class).

Is there any better way to store table sheet data type presented in this example? Preserving all values in their own entity properties is not an option, because there will be plenty of table data in that form.

Upvotes: 1

Views: 957

Answers (2)

Nikola Loncar
Nikola Loncar

Reputation: 2671

I have tried couple of solutions and this is best result by my opinion:

Step 1.

Creation of macro for generating tableSheet in separate twig file (for later usage in other forms).

{# in Default:form.html.twig #}
{% macro tablesheet(name, rows, colums, titles) %}
   ... titles header ...
   {% for i in 1..rows %}
      {% for j in 1..colums %}
   <input name="{{ name }}_{{ i }}{{ j }}" type="text" class="flat-form" />
      {% endfor %}
   {% endfor %}
{% endmacro %}

Step 2.

Import macro and create tables of input fields, in add/edit template :

{% import "ProjectSomeBundle:Default:form.html.twig" as forms %}
...
{{ form_widget(form) }}
{{ forms.tablesheet('table1', 4, 3, {0:'col1', 1:'col2', 2:'col3'}) }}
{{ forms.tablesheet('table2', 7, 3, {0:'col1', 1:'col2', 2:'col3'}) }}
...
</form>

Step 3.

Create jQuery function to serialize/deserialize form (input elements with flat-form class attr in this case). For serilize I used something like this http://css-tricks.com/snippets/jquery/serialize-form-to-json/ . Serialized values are stored in single entity filed as string and saved to db like that.

How it's works :

on opening edit form, jQuery deserialized data from that entity field and loaded to tablesheet input fields. Before sending it back (post) to server values are collect and put in that same field via serialized function.

Upvotes: 1

Nicolai Fr&#246;hlich
Nicolai Fr&#246;hlich

Reputation: 52513

You should create an entity class with x , y and value properties.

x & y being unique combinations, representing the position in your matrix.

This entity does not have to be stored in your database and can only be used to generate the form.

Then create a form-collection which renders your fields in this matrix form.

Finally: use a DataTransformer to transform the collection of entities to an array as desired.

Now save the array in your database.

Upvotes: 4

Related Questions