我想从数据库值中减去输入字段值 怎么管理? 我需要在MVC中做些什么改变? 我在myform.ctp中的代码如下:
echo $this->Form->input('discount', array('label' => 'Discount'));
$val1 = //---------here the input value ---------//
$val2 = $this->data['Product']['price']; //value from database
$val3 = $val2 - $val1;
echo $val3;
:
<?php
echo $this->Form->input('discount', array('id'=>'n','label' => 'Discount %','placeholder'=>'Value in %'));
echo $this->Form->hidden('price', array('id'=>'p'));
echo $this->Form->input('finalprice', array('id'=>'c'));
?>
<script>
var a=document.getElementById('n').value;
document.write(a);
var b=document.getElementById('p').value;
document.write(b);
var c=b-a;
document.getElementById('c').value=c;
document.write(c);
</script>
现在我获取输入值,进行操作,但我需要将最终值插入数据库字段... data ['Product'] ['finalprice'] .........如何那样做?
答案 0 :(得分:0)
首先在控制器
处设置值 $this->set('val1',$this->data['Product']['price']);
然后在视图中
<input type="hidden" value="<?php echo $val1; ?>" id="val1">
<?php echo $this->Form->input('discount', array('label' => 'Discount','id'=>'val2')); ?>
<script>
$(document).ready(function(){
var finalval=parseInt($('#val1').val())-parseInt($('#val2').val());
alert(finalval);
});
</script>
答案 1 :(得分:0)
在您的Product
模型中编写代码,这是Cakephp的内置功能
public function beforeSave($options = array()) {
if (!empty($this->data['Product']['discount']) &&
!empty($this->data['Product']['price'])
) {
$this->data['Product']['finalprice'] =
$this->data['Product']['price'] - $this->data['Product']['discount'];
}
return true;
}
在cakephp中查看Manual beforeSave
函数。