Вопрос

I have two models, Component and Group. A Group has many Components, and a Component can be in many Groups. Now, what I need is a view, in which there's a table, n times m field (or matrix) of checkboxes. The Columns would be all the Groups (which would be fewer) and the rows would represent the Component. Basically, when the HaBTM-Relationship exists, the checkbox is checked.

This should be editable, meaning it would be wrapped in a form.

      | Group 1 | Group 2 | Group 3
 C1   |    x    |         |   x
 C2   |    x    |    x    |
 C3   |         |         |   x

What is the least stressful way to achieve this in CakePHP?

Это было полезно?

Решение

Alright. First of course you load the data from your connecting table. So you get a lot of datasets like:

id => 4
component_id => 4
group_id =>3 

Then you have an array of all existing components and another one which contains all existing groups.

Since you have the components in rows I would reorganise this array of arrays, so that you have a multidimensional array which as first key has the component_id and under this id you have an array containing the arrays of all datasets, which contain this group.

e.g.:

array(
1 => array(
    0 => array(
    'id' => 4,
    'component_id' => 1,
    'group_id' => 2,
    ),
    1 => array(
    'id' => 4,
    'component_id' => 1,
    'group_id' => 5,
    ),
    ),
2 => array(
    0 => array(
    'id' => 4,
    'component_id' => 2,
    'group_id' => 1,
    ),
    1 => array(
    'id' => 4,
    'component_id' => 2,
    'group_id' => 3,
    ),
    ),
);

After this reorganisation you can pass it to the view, where you can iterate through it to build the form, giving each checkbox the component-group info, which you can collect after sending the form.

Nicer than that (as a version 1.2) would be a AJAX call which saves the combination immediately after activating or deactivating the checkbox. Your choice ;)

Calamity Jane

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top