kuki
kuki

Reputation: 79

cakephp save data into another table

i have a input-field with a value from a controller (ControllerA). Now i want to save only the input-field into another table.

ControllerA:

public function makeentry($id = null, $value){

    //Here i get the correctly value in the input field 
    $controllerA = $this->ControllerA->get($id);

    //Connect to the other table (?)
    $controllerBTable = TableRegistry::get('ControllerB');
    $controllerB = $controllerBTable->newEntity();

    //Dosn't work here and no error message
    if ($this->request->is('post')) {

            $controllerB->name = $this->request->data;

            if ($controllerBTable->save($controllerB)) {
                $this->Flash->success(__('Saved.'));

                //Go back to ConntrolerA
                return $this->redirect(['action' => 'index']);
            }else{
                $this->Flash->error('Could not be saved.');
            }               
        }

        //set the value into the input-field
        $this->set('controllerA', $controllerA);
    }
}

in the model->table

TableA:

public function initialize(array $config)
    {
        $this->table('tableA');
        $this->displayField('name');
        $this->primaryKey('id');
        $this->belongsTo('TableB');
    }

TableB:

public function initialize(array $config)
    {
        $this->table('tableA');
        $this->displayField('name');
        $this->primaryKey('id');
        $this->belongsTo('TableA');
    }

Can someone explain it in simple words or example code how to realize it

Upvotes: 0

Views: 2201

Answers (1)

Akshay Sharma
Akshay Sharma

Reputation: 1112

You can follow these steps
Save data in table 1

    $saveData = $this->request->data;
    $this->loadModel('Table1');
    $this->Table1->save($saveData);

Similarly you can save data in any table

    $saveData = $this->request->data;
    $this->loadModel('Table2');
    $this->Table2->save($saveData);

You can either select this one also

    $saveData = array();
    $saveData['field_name_1'] = $this->data[$this->modelClass]['field_name_1'];
    $saveData['field_name_2'] = $this->data[$this->modelClass]['field_name_2'];
    $this->{$this->modelClass}->save($saveData);

Upvotes: 1

Related Questions