When saving belongsTo data does not work with CakePHP 3
Thursday, November 7, 2019, 11:27 AM
Make sure that you are exposed the belongsTo entity as an accessible field in the saved entity.
Example:
UnitType belongsTo BaseUnit (src/Model/Table/UnitType.php):
...
public function initialize(array $config)
{
...
$this->belongsTo('BaseUnits', [
'foreignKey' => 'base_unit_id',
'className' => 'Units',
'joinType' => 'INNER'
]);
BaseUnit added as an accessible field in src/Model/Entity/UnitType.php
protected $_accessible = [
'name' => true,
'base_unit_id' => true,
'base_unit' => true,
'created_by' => true,
'modified_by' => true,
'units' => true,
'item_types_attributes' => true,
'items' => true
];
Form:
<?php
echo $this->Form->control('name', ['label' => __('Mennyiségi egység neve (pld. térfogat)'
]);
?>
<h4><?= __('Alapértelmezett mértékegység'
?></h4>
<?php
echo $this->Form->control('base_unit.name', ['label' => __('Mértékegység neve (pld. liter)'
]);
echo $this->Form->control('base_unit.short_name', ['label' => __('Mértékegység rövid neve (pld. l)'
]);
?>
Saved with the following method in the controller:
$unitType = $this->UnitTypes->newEntity();
if ($this->request->is('post'
) {
$unitType = $this->UnitTypes->patchEntity(
$unitType,
$this->request->getData(),
['associated' => ['BaseUnits']]
);
if ($this->UnitTypes->save($unitType)) {
[ hozzászólás ] [ 0 trackbackek ] permalink ![](themes/simple/images/stars/full_star.png)
![](themes/simple/images/stars/full_star.png)
![](themes/simple/images/stars/half_star.png)
![](themes/simple/images/stars/no_star.png)
( 3 / 1202 )
<< <Előző | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Következő> >>