1

I am wondering how to reset a field to the DEFAULT value (the one set in MySQL structure) when performing an update action in CakePHP. Like using the DEFAULT keyword in SQL:

INSERT INTO items (position) VALUES (DEFAULT);

edit: I am not searching for a way to use the default on create, I am rather looking for a way to reset the field to it's default when it has been already used.

lorem monkey
  • 3,942
  • 3
  • 35
  • 49

2 Answers2

1

You can simply unset the form input from the requested array, if you want to save its default value into the mysql database. You can try the following to achieve the same:

$item_details = $this->request->data;
unset($item_details['Item']['position']);
$this->Item->create();
$this->Item->save($item_details);

According to your edited question, if you want to reset any field during updating a record. you just need to use the MySql default() function.

$item_details = $this->request->data;
$this->Item->id = $item_details['Item']['id'];
$this->Item->saveField('position', DboSource::expression('DEFAULT(position)'));
Arun Jain
  • 5,476
  • 2
  • 31
  • 52
  • I think my question is a bit misleading. I didn't mean the create process - this is clear how to use the default values. I am searching a way to reset the default value on an update. (I'll rephrase my question now, sorry) – lorem monkey Aug 14 '12 at 06:51
  • Does not work. Cakep tries to save 'DEFAULT(position)' to my INT field and so it is 0. – lorem monkey Aug 14 '12 at 09:20
  • Kindly check, if there is any default value for the `position` field you specified. Try with any other field. It will work just fine. What you actually needed to save? – Arun Jain Aug 14 '12 at 09:52
  • It did save - but it did not save the default of 9999 which I have set (and is used on create). It saved 0, because it tried to save a string into the INT field. I have added a new answer by myself with a working example. Thank you for help after all :) – lorem monkey Aug 14 '12 at 10:02
0

To answer my own question, it could be done with:

$this->Item->saveField('position', DboSource::expression('DEFAULT(position)'));

or

$data['Item']['position'] = DboSource::expression('DEFAULT(position)');
$this->Item->save($data)

But - and here we go with the lost hours: to be able to use DboSource there had to be a database query before! Otherwise CakePHP throws the error Class 'DboSource' not found.

lorem monkey
  • 3,942
  • 3
  • 35
  • 49