PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] CakePHP 3.x: saving one input into multiple tables

 February 21, 2022     cakephp, cakephp-3.0, save     No comments   

Issue

I´m sorry I have to ask again, but I´m struggling with saving one input into two tables.

My first table:

deceases
 - id
 - other records
 - funeral_id
 - cemetery_id

My second table:

funerals
 - id
 - other records
 - cemetery_id

My third table:

cemeteries
 - id
 - other records

The associations:

One decease belongs to a funeral. A funeral has many deceases.
One decease belongs to a cemetery. A cemetery has many deceases.
One funeral belongs to a cemetery. A cemetery has many funerals.

In the add-action of the DeceasesController I want to save the cemetery_id into deceases and into funerals with one only input.

The other inputs into deceases and funerals are saved very well, but I don´t understand the documentation of CakePHP how to save the cemetery_id, too.

DeceasesController:

public function add() {

        $decease = $this->Deceases->newEntity();
        if ($this->request->is('post')) {
            $decease = $this->Deceases->patchEntity($decease, $this->request->data, [
                'associated' => [
                    'Funerals', 
                    'Cemeteries' 
                ]
            ]);
            if ($this->Deceases->save($decease)) {
                $this->Flash->success(__('Saving successfully.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('Saving wasn´t successful. Try again.'));
            }
        }

        $cemeteries = $this->Deceases->Cemeteries->find('list', ['limit' => 300]);
        $funerals = $this->Deceases->Funerals->find('list', ['limit' => 200]);
        $this->set(compact('decease', 'cemeteries', 'funerals'));
        $this->set('_serialize', ['decease']);
    }

Snippet of add.ctp:

echo $this->Form->input('funeral.cemetery_id', ['options' => $cemeteries, 'label' => 'cemetery']);

I hope, you´re able to understand my issue. English isn´t my first language.

Thanks in advance.


Solution

Hope I have understood your question:

In your controller right after patchEntity and before saving you can do

$decease->cemetery_id = $decease->funeral->cemetery_id;

So the same value will be set both for decease and for funeral



Answered By - arilia
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing