I would like to do the following: in admin.php, when I click delete button on a row, instead of deleting the record, I would like to update a datetime field in the database. How can I do it? I was trying a code what was working once or twice but since then it’s not working, however I don’t think I have changed anything. I’ve deleted assets folder but still not working. I was playing so much with code that I don’t know which was the working version.
here is the code in projectcontroller:
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
//$this->loadModel($id)->delete();
$model = $this->loadModel($id);
$model->mrsktd = new CDbExpression('NOW()');
$model->save();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
no-no, there is no 400 exception, the page is reloaded without any problems, it’s just that save() fails to update the timestamp.
with this:
$model->save(false);
now it seems to work. thank you very much! but why? I’m sure I was not trying this and it used to work before…
now I understand that problem is with validation. I’ve checked what to do but it seems not so easy to validate a MySql format datetime (yyyy-MM-dd HH:mm:ss)…
Because CDbExpression(‘NOW()’) will set the literal string of ‘NOW()’ to ‘mrsktd’, it won’t match the format of the date validator.
But I think there’s no harm to skip validation by $model->save(false) in this particular case.
The validation of the model is meant for checking the user input. Basically there’s no need to validate when the value is set by the program. Or, you may define ‘safe’ for ‘mrsktd’ if the field has no chance to get the user input.