I'm using callback beforeSave
to format the date from d/m/Y
to Y-m-d
. Date is being saved as Y-d-m
instead of Y-m-d
. Syntactically the code is right.
The date is in the table as date.
beforeSaveData function
Please note that I have $data
debug before formatting and after formatting. Before formatting, the date is correct, after formatting, the month assumes the value of the day and the value of the day assumes the month. Ex: 10/01/2016, it stays like: 2016-10-01, that is, it is the first of October.
AppModel:
public function beforeSaveData($data) {
debug($data);
$data = date('Y-m-d', strtotime($data));
debug($data); die();
return $data;$data;
}
Expense Model:
public function beforeSave($options=>array()) {
$this->data['Despesa']['valor_despesa'] = $this->beforeSaveValor($this->data['Despesa']['valor_despesa']);
$this->data['Despesa']['data_despesa'] = $this->beforeSaveData($this->data['Despesa']['data_despesa']);
return true;
}
No controller:
public function inserirDespesa() {
if ($this->request->isPost()) {
if ($this->Despesa->save($this->request->data)) {
$this->Session->setFlash("Despesa inserida");
}
else {
$this->Session->setFlash("Despesa não inserida");
}
}
}
And also follows the view. The date in the view is as type=text
because I have regular functions in javascript
for date and monetary value.
<html>
<body>
<?php
echo $this->element('menuDespesas');
//echo $this->Html->script('inserir_despesa');
?>
<script>
function mascara(o, f) {
obj=o;
fun=f;
setTimeout("execMascara()", 1);
}
function execMascara() {
obj.value=fun(obj.value);
}
function data(data) {
data=data.replace(/\D/g,""); // Remove tudo o que não é dígito//
data=data.replace(/^(\d{2})(\d)/,"$1/$2"); // Coloca barra entre o 2° e o 3°
// digito//
data=data.replace(/(\d{2})(\d)/,"$1/$2"); // Coloca barra entre o 4° e o 5°
// dígito//
return data;
}
function valor(valor){
valor=valor.replace(/\D/g,"");
valor=valor.replace(/(\d)(\d{2})$/,"$1,$2");
return valor;
}
</script>
<h2>INSERIR DESPESA</h2><p>
<?php
echo $this->Session->flash();
echo $this->Form->create('Despesa');
echo $this->Form->input('despesa', array('label'=>'Despesa:', 'maxlength'=>'30'));
//campo valor_despesa do tipo texto para aceitar a "," (vírgula).
echo $this->Form->input('valor_despesa', array('label'=>'Valor (apenas números, incluindo os centavos. Coloque 00 quando não houver centavos):', 'maxlength'=>'10', 'type'=>'text', 'onkeypress'=>"mascara(this, valor)"));
//data_despesa com type=text para possibilitar a digitação e o símbolo de "/".
echo $this->Form->input('data_despesa', array('label'=>'Data:', 'type'=>'text', 'maxlength'=>'10', 'onkeypress'=>"mascara(this, data)" ));
echo $this->Form->input('local_despesa', array('label'=>'Local da despesa', 'maxlength'=>'15'));
echo "<p>";
echo $this->Form->submit('Inserir despesa');
echo $this->Form->button('Limpar', array('type'=>'reset'));
echo $this->Form->end();
?>
</body>
</html>