テキストリンクの様な見た目でPOSTデータを送信できるFormヘルパー、postLink()について備忘録代わりにポストします。
FormHelper::postLink()
使い所
テキストリンクを用いてDBレコードの削除、
リンククリック時にDBを更新してしまうものなどに使うと効果的。
サブミットボタンではなく、あくまでもテキストリンクのクリックをトリガーに値の送信を行いたい場合に便利。
書式
| 1 | $this->Form->postLink($title, $url, $options, $confirm); | 
| プロパティ | 初期値 | 詳細 | 
|---|---|---|
| $title | 省略不可 | リンクに表示される文字列 | 
| $url | null | リンク先(アクション)及び引数。 引数はControllerのActionの引数として受信可能 | 
| $options | array() | フォームオプションの他、array(‘data’)が使用可能 | 
| $confirm | false | 確認アラートに表示される文字列 | 
実例
| 1 2 3 4 5 6 | echo $this->Form->postLink(     '削除',     array('action'=>'delete', $post_id),     array('class'=>'btn btn-warning btn-xs'),     '削除してよろしいですか?' ); | 
Controller側の処理
以下のif文でGETでのアクセスを防ぐと幸せになれます。
引数はアクション内で普通に受信できます。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public function delete($post_id=null) {     if ($this->request->is('get')) {         // GETアクセスだった場合の処理(→500とか出せばいい感じ?)         throw new InternalErrorException('投稿の削除に失敗しました');     }     $this->Post->id = $id;     if (!$this->Post->exists()) {         throw new NotFoundException('見つかりませんでした');     }     $this->Post->delete($post_id);     $this->redirect(array('controller'=>'posts', 'action'=>'index')); } | 
参考
公式サイトリファレンス
FormHelper – 2.x – postLink()
![]()
FormHelper - 2.x
The FormHelper focuses on creating forms quickly, in a way that will streamline validation, re-population and layout.
フォームのオプションについてはこちら

 
         
         
         
         
         
         
         
         
         
         
         
         
         
         
  
  
  
  

