環境
PHP 7.2.21
CakePHP 2.10.18
やりたいこと
formタグの外にあるボタンやリンクを押下した時もcontrollerにpostで値を渡したい
やったこと
test.ctp
<?= $this->Form->create('HogeList', ['type' => 'GET']); ?>
<div class="searchInputArea" style="margin-bottom: 0px;margin-top: 0px;">
<table class="em9">
<tr>
<th>
ID
</th>
<td>
<?php
echo $this->Form->input('id', [
'type' => 'text',
'id' => 'item_id',
'size' => 30,
'label' => false,
'div' => false,
'empty' => true,
'required' => false,
]);
?>
</td>
</tr>
<tr>
<th>
名前
</th>
<td>
<?php
echo $this->Form->input('name', [
'id' => 'name',
'type' => 'text',
'size' => 30,
'label' => false,
'div' => false,
'empty' => true,
'required' => false,
]);
?>
</td>
</tr>
<tr>
<th>
ステータス有効のみ
</th>
<td>
<?php
echo $this->Form->input('status', [
'type' => 'checkbox',
'div' => false,
'value' => TestAppModel::STATUS_ACTIVE,
'label' => '',
]);
?>
</td>
</tr>
</table>
</div>
<div class="submitArea hasSubAction">
<ul class="submitButtons">
<li>
<label class="submitBase primary" for="submit">
<?php echo $this->Form->hidden('mode', ['value' => '']); ?>
<?php
echo $this->Form->submit('検索', [
'type' => 'submit',
'id' => 'submit',
'div' => false,
'label' => false
]);
?>検索
</label>
</li>
</ul>
</div>
<?php echo $this->Form->end(); ?>
</div>
test.ctp
<!--formの外に追加-->
<?php echo $this->Html->link('formの値を送信した使いたいリンク', 'javascript:clickOutOfFormLink();void(0)', ['class' => 'actionBtnBase hogeListOutput']); ?>
<!--jQuery部分-->
<script>
// スコープ外から検索ボタンを押下
function clickOutOfFormLink() {
// 検索機能をform外の処理に切り替えるためhiddenを設定
$('#HogeListMode').val('hogehoge');
document.getElementById('submit').click();
// 検索機能に戻すためhiddenをクリア
$('#HogeListMode').val('');
}
</script>
結果
controllerにhiddenを含めてpost送信されているので
これを元に押下されたボタンの判断が可能
TestController.php
/**
* 一覧
*
* @return void
*/
public function index(): void
{
if (Hash::get($this->request->query, 'mode') === 'hoge') {
// modeがhogeである場合はform外のリンクが押下されている
echo 'hoge';
// 入力値も使用可能🐈
var_dump($this->request->query);
}
}