Rule in model to format date

Asked

Viewed 491 times

1

I have two rules in two camps.

In the data_expense field, I want to take the format d/m/a and move on to a-m-d. Turns out when you save it on the bench, it’s like 0000-00-00. I don’t know how to debug the model to see how it is transforming and the controller, when debugging the $this->request->data) does not use validation.

The field valor_despesa is ok. You are changing from "," to ".". The problem is only in formatting data_despesa.

What’s wrong with it?

Follow the model code:

<?php

class Despesa extends AppModel {

    public $name='despesa';
    public $useTable='despesas';
    public $primaryKey='id_despesa';

    public $validate=array(
'data_despesa'=>array(  
    'data'=>array(
'rule'=>array('data'))),

'valor_despesa'=>array( 
'preco'=>array(
'rule'=>array('preco'))));

    public function data($check) {
        $dataDespesa=explode("/", $check['data_despesa']);

        $dataDaDespesa="";

        $dataDaDespesa=$dataDespesa[2]."-".$dataDespesa[1]."-".$dataDespesa[0];

        return true;
    }  

    public function preco($check) {
        $valorDespesa=str_replace(",", ".", $check['valor_despesa']);

        return true;
    }

}
?>
  • Use <pre><code> to format the question, the prettify of the site does not work: http://answall.com/editing-help

  • the field data_despesa is with the guy date in the Database? If yes, the format yyyy-MM-dd is the default format of the 'date' fields. What you can do is model this value to show on the screen, but the date fields will always save in this format in the Database. If it were possible to save anyway, the Database would have problems comparing two dates.

  • @Dennne what I want is to change from d/m/a to y-m-d I got in the controller, but in the model, I can’t. It was a wonder this validation in the controller, so I want to implement in the model.

1 answer

2

To change the date format of an object DateTime which cake probably uses, use the method format().

Change:

public function data($check) {
    $dataDespesa=explode("/", $check['data_despesa']);
    $dataDaDespesa="";
    $dataDaDespesa=$dataDespesa[2]."-".$dataDespesa[1]."-".$dataDespesa[0];
    return true;
} 

for:

public function data($check) {
    $dataDespesa = $check['data_despesa']->format('Y-m-d');
    return true;
} 

I don’t know the cake, maybe it’s necessary to change the return true for return $dataDespesa.

How to format monetary values in PHP see that answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.