Reputation: 965
I would like to iterate and edit data from a pivot table in edit.ctp
.
Displaying and editing one entity works fine with the code below (if there is at least one entry):
edit.ctp
echo $this->Form->control('winkels.0._joinData.winkel_id', [
'options' => $winkels,
'label' => 'Winkel',
'type' => 'select'
]);
echo $this->Form->control('winkels.0._joinData.url');
echo $this->Form->control('winkels.0._joinData.prijs');
I could get the depth of the array and change the index of winkels
, but that's just dirty... I am not even sure if that would work.
So I tried the code below but it does not create the right HTML:
if(!empty($product->winkels)) {
foreach ($product->winkels as $winkel) {
echo $this->Form->control($winkel->_joinData->winkel_id, [
'options' => $winkels,
'label' => 'Winkel',
'type' => 'select'
]);
echo $this->Form->control($winkel->_joinData->url, [
'label' => 'URL',
'value' => $winkel->_joinData->url
]);
echo $this->Form->control($winkel->_joinData->prijs, [
'label' => 'Prijs',
'value' => $winkel->_joinData->prijs
]);
}
}
Is there a clean way the generate these controls for the pivot table? Also if $product->winkels
is empty, how do I make the first entry?
Additional info:
--- EDIT ---
I have adjusted my code, but I seems that it fails to create the "pivoting table"
if(!empty($product->winkels)) {
foreach ($product->winkels as $index => $winkel) {
echo $this->Form->control('winkels.$index.winkel_id');
echo $this->Form->control('winkels.$index._joinData.winkel_id', [
'options' => $winkels,
'label' => 'Winkel',
'type' => 'select'
]);
echo $this->Form->control('winkels.$index.url', [
'value' => $winkel->_joinData->url]
);
echo $this->Form->control('winkels.$index.prijs', [
'value' => $winkel->_joinData->prijs]
);
}
} else {
echo $this->Form->control('winkels.0.winkel_id');
echo $this->Form->control('winkels.0._joinData.winkel_id', [
'options' => $winkels,
'label' => 'Winkel',
'type' => 'select'
]);
echo $this->Form->control('winkels.0._joinData.url');
echo $this->Form->control('winkels.0._joinData.prijs');
}
As you can see in the debug result, a lot of the structure is missing:
Upvotes: 0
Views: 51
Reputation: 60463
There's nothing dirty about using the array's index, that's actually exactly how you'd do it, ie something along the lines of:
foreach ($product->winkels as $index => $winkel) {
echo $this->Form->control("winkels.$index.id");
echo $this->Form->control("winkels.$index._joinData.winkel_id", [/* ... */]);
echo $this->Form->control("winkels.$index._joinData.url", [/* ... */]);
echo $this->Form->control("winkels.$index._joinData.prijs", [/* ... */]);
}
Also don't forget the primary key if you want to update existing records! And note that you don't need to provide the value, the form helper will find the value itself based on the given field name.
And if winkels
is empty, then you simply start with the index 0
, just like in your first example.
See also
Upvotes: 1