KAEDE Hack blog

JavaScript 中心に ライブラリなどの使い方を解説する技術ブログ。

Form Cheat Sheet CakePHP

Form Cheat Sheet ~ 覚書 ~

why

I got err.

Notice (8): Undefined variable: ledger 
[APP/Template/Ledgers/edit.ctp, line 20]

in edit.ctp Line 20:
<?= $this->Form->create($ledger) ?>

I did not how GET or POST data send.
So I dicided to write down GET and POST basic.

concept

List basic CRUD usage by MIN examples
use Ledger TABLE.

index (pass data)

Controller

public function index(){
    $ledgers = $this->paginate($this->Ledgers);
    // or $this->Ledgers->find('all'));
    $this->set(compact('ledgers'));
}
  • take all record by arr from ledgers table.
  • and pass ctp $ledgers by set(compact('hoge')) method.

    ctp

<?php foreach ($ledgers as $ledger): ?>
<?= h($ledger->customer_name) ?>
  • select values by foreach() form the $ledgers and print each ledgers column record.

edit form (update)

index.ctp

<?= $this->Html->link(__('Edit'), 
['action' => 'edit', $ledger->id]) ?>

This sending GET to edit.ctp!
passing this url:
http://localhost:8765/ledgers/edit/2

Controller/edit()

$ledger = $this->Ledgers->get($id);
debug($this->request->params['pass'][0]);
// GETの場合
debug($this->request->query);
// POSTの場合
debug($this->request->data);
  • Returns id sent by GET

Form

Controller

In LedgersController/edit/:

$passedArgs = $this->request->params['pass'][0];
debug($passedArgs); // 2
debug($this->request->is('get')); // true.
        $ledger = $this->Ledgers->get($id);

        // this is POST only -------------
        if ($this->request->is(['patch', 'post', 'put'])) {

            $ledger = $this->Ledgers->patchEntity(
                $ledger, $this->request->getData());
            if ($this->Ledgers->save($ledger)) {
                $this->Flash->success(
                    __('The ledger has been saved.'));

                return $this->redirect(
                    ['action' => 'index']);
            }
            $this->Flash->error(
                __('The ledger could not be saved.'));
        }
        $this->set(compact('ledger'));

that was GET method.

This save data to DB.

blogs.windows.com