cakephp post処理まとめ

viewで項目名を羅列するのがめんどくさい場合

<?php
echo $this->Form->create(‘モデル名’);
echo ‘<div class=”form-inline”>’;
echo ‘<div><button class=”btn btn-primary btn-sm” type=”submit” name=”action” value=”save”>保存</button></div>’;
echo ‘</div>’;
$datas = $this->Form->value()[‘value’];
//又は $datas = $this->request->data[‘モデル名’];
foreach($datas as $key=>$val){
if(‘password’==$key) continue;
echo $this->Form->input($key);
}
echo $this->Form->end();
?>

 

viewのselect要素の選択肢をcontrollerで設定

■controller
$this->request->data[‘モデル名’][‘op’][‘モデル名.カラム名’] = [‘0’=>’選択肢1′,’1’=>’選択肢2’];
■view
echo $this->Form->input(‘カラム名’, [‘class’=>’form-control’,’options’=>$this->request->data[‘op’][‘モデル名.カラム名]]);

 

postの仕方

①普通にformで囲んだ要素でpost

■view
<?php
echo $this->Form->create(‘モデル名’);
echo ‘<div><button class=”btn btn-primary btn-sm” type=”submit” name=”action” value=”save”>保存</button></div>’;
echo $this->Form->input(’カラム名’);
echo $this->Form->end();
?>
■controller
$this->request->data[‘モデル名’]に入っている。

 

②javascriptで無理やりformを作り任意の要素をpost

■view
$(‘<form/>’,{action:url’,method:’post’})
.append($(‘<input/>’,{type:’hidden’,name:’data[モデル名][カラム名1]’,value:値1}))
.append($(‘<input/>’,{type:’hidden’,name:’data[モデル名][カラム名2]’,value:値2}))
.append($(‘<input/>’,{type:’hidden’,name:’data[モデル名][カラム名3]’,value:値3}))
.append($(‘<input/>’,{type:’hidden’,name:’data[モデル名][カラム名4]’,value:値4}))
.appendTo(document.body).hide().submit().remove();
■controller
$this->request->data[‘モデル名’]に入っている。

 

③ajaxでformに囲まれた要素をpost

■view
var postdata = $(formid).serialize();
var param = {url: url, type: ‘post’,data:postdata};
$.ajax(param)
■controller
$this->request->data[‘モデル名’]に入っている。

 

④ajaxで任意の要素をpost

■view
var postdata = {モデル名:{カラム名:値1}};
var param = {url: url, type: ‘post’,data:postdata};
$.ajax(param)
■controller
$this->request->data[‘モデル名’]に入っている。

 

⑤ajaxでformに囲まれた要素と任意の要素をpost

■view
var hoge = {};
hoge[‘post’] = $(formid).serializeArray()
hoge[‘handson’]=$(‘#hot1’).handsontable(‘getSourceData’);
var postdata = {data:JSON.stringify(hoge)};
var param = {url: url, type: ‘post’,data:postdata};
$.ajax(param)

■controller
$decoded = json_decode($this->request->data,true);
$handson = $decoded[‘handson’];
$postparam = $decoded[‘post’];
//下記でcakephpの$this->request-data配下の形に変換
$cakepostdate = [];
foreach($postparam as $val){
if(strpos($val[‘name’], ‘data[‘) !== 0) continue;
preg_match_all(‘/\[(.*?)\]/’, $val[‘name’], $matches);
$key = implode(‘.’,$matches[1]);
if($this->Common->endsWith($val[‘name’],'[]’)){
$key = substr($key, 0, -1);
if(!is_array($cakepostdate[$key])){
unset($cakepostdate[$key]);
}
$cakepostdate[$key][] = str_replace(“\t”,””,trim($val[‘value’]));
}else{
$cakepostdate[$key] = str_replace(“\t”,””,trim($val[‘value’]));
}
}
$cakepostdate = Hash::expand($cakepostdate);