0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cakephp2でボタンにクエリ付きのリンクを表示させたかった

Posted at

ボタンっていう形を保ってクエリ付きのURLを生成させたかった。

他にもボタンの作り方はあってやり方はあるのだろうが、自分にとってはこの書き方が都合が良かったので記事にする。

コード

<?php
 //urlの生成
  $queries = ["id"=>$data['model']['id'], "name"=>$data['model']['name']];
  $url = $this->Html->url(['controller'=>'action', 'action'=>'action', "?"=>$queries]); 
?>
<!-- ボタン生成 -->
<button type="button" onclick="location.href='<?= $url ?>'">button</button>

[FormHelper - 2.x]
(https://book.cakephp.org/2/ja/core-libraries/helpers/form.html)
実際に書いてみると、何に悩んでいたのかわからないレベルに当然っちゃ当然だなって感じになった。

サンプルコード


<?php
/* Controller.php */
public function index(){
 //仮のデータ
 $datas = array(
     0 => array(
         'model' => array(
             'id' => 0,
             'name' => 'zero'
         ),
     ),
     1 => array(
         'model' => array(
             'id' => 1,
             'name' => 'one'
         ),
     ),
     2 => array(
         'model' => array(
             'id' => 2,
             'name' => 'two'
         ),
     ), 
  );
  $this->set('datas', $datas);
}

?>

<!-- view.ctp -->
<table>
    <tr>
        <th>id</th>
        <th>name</th>
        <th>buttons</th>
    </tr>
    <?php foreach($datas as $data): ?>
        <tr>
            <?php
                $queries = ["id"=>$data['model']['id'], "name"=>$data['model']['name']];
                $url = $this->Html->url(['controller'=>'controller', 'action'=>'action', "?"=>$queries]); 
            ?>
            
            <td><?= $data['model']['id'] ?></td>
            <td><?= $data['model']['name'] ?></td>
            <td><button type="button" onclick="location.href='<?= $url ?>'">button</button></td>
        </tr>
    <?php endforeach; ?>
</table>

実行結果

スクリーンショット 2020-10-24 20.46.26.png
上記のサンプルコードはこのような表となって出力されるはず。

スクリーンショット 2020-10-24 20.47.19.png
ボタン要素には、リンクが生成されてそこから飛ぶようになってる事が確認できた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?