Saturday, December 13, 2014

Re: 3.0 - How to add a form data using its primarykey to its associated tables

Ah ok. I understand the question now. Instead of using newEntity() you should use patchEntity()

$unitId = $this->Units->get($uId);
$unit = $this->Units->patchEntity($unitId, $this->request->data(),['associated' => ['Costs', 'FixedCosts']]);


On Thursday, December 11, 2014 5:08:27 PM UTC+1, Bayezid Alam wrote:
Hi,


i have Tables :

Units hasOne costs & hasOne fixed_costs

i want to add data to costs and fixed_costs table using units's primary key from units Controller.

i did below things but its creating a new record at unit Table instead of using primaryKey

Form at unitsController:

<?php

echo $this->Form->create($unit);
echo $this->Form->input('cost.rental_cost');
echo $this->Form->input('fixed_cost.gas_bill');
echo $this->Form->input('fixed_cost.water_bill');
echo $this->Form->input('fixed_cost.service_bill');
echo $this->Form->button('Save Costs');
echo $this->Form->end();

?>

Function at UnitsController:

public function add_cost($uId){
        if (!$uId){
            throw new NotFoundException(__('Unit id Not found, try with a valid ID'));
        }
        
        $unitId = $this->Units->get($uId);
        
        $unit = $this->Units->newEntity($this->request->data(),['associated' => ['Costs', 'FixedCosts']]);
        
        if ($this->request->is('post')){
            $unit->cost->unit_id = $unit->fixed_cost->unit_id = $unitId->id;
            if ($this->Units->save($unit)){
                $this->Flash->success(__('The unit cost has been added'));
                return $this->redirect(['controller' => 'houses', 'action' => 'view', $unit->house_id]);
            }
        }
        
        $this->set(compact('unit'));
    }

Please suggest me on this regard.

Thanks
Bayezid

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: