SupremeDud
SupremeDud

Reputation: 1411

Modifying cakephp request->data array

I'm trying to learn cake with a simple blog. I used cake bake to make my controllers. The Post model has a created_date field, but I want to set that on the server side (a client could tamper with it). I've added a couple lines to the add controller like so:

public function add() {
    if ($this->request->is('post')) {
      $this->Post->create();
      date_default_timezone_set("UTC");
      $this->request->data['Post']['created_date'] = date("c"); //set create date server side
      if ($this->Post->save($this->request->data)) {
        $this->Session->setFlash(__('The post has been saved.'));
        return $this->redirect(array('action' => 'index'));
      } else {
        $this->Session->setFlash(__('The post could not be saved. Please, try again.'));
      }
    }
    $authors = $this->Post->Author->find('list');
    $tags = $this->Post->Tag->find('list');
    $this->set(compact('authors', 'tags'));
  }

The problem is the created date isn't saved at all, it's set to 0000-00-00. Everything I read says that this should be good. Even when I look at debugkit, it shows the post data has the correct created_date in the array.

Upvotes: 1

Views: 1294

Answers (2)

user3698702
user3698702

Reputation: 46

What is your field type for the date.. is it datetime or is date.. and what is the accepted format in the database.. You can try insert one date into the table to see the format.

I have similar problem, date shows 0000-00-00, but then I realized I have to follow the format based on database. If your date is from a form, just use the following to convert it to the correct format.

$date = date('Y-m-d',strtotime($this->request->data['Model']['date']));

Change the date format accordingly.

Upvotes: 0

Colonel Mustard
Colonel Mustard

Reputation: 1533

If you follow cakephp's conventions then the framework will automatically populate this field for you. You have two options:

  1. rename the field you want to 'created' and set it to datetime in the database, and the framework will take care of the rest, provided you don't manually pass a value via the posted data

  2. Use this: $this->request->data['Post']['created_date'] = DboSource::expression('NOW()');

Upvotes: 5

Related Questions