Hello everyone,
I am having a bit of trouble with some code. I have a model Contents and I have added an "actionDeleteMultiple" to its controller, which takes an array of content IDs and deletes them. Here is the code:
public function actionDeleteMultiple()
{
if(Yii::app()->request->isPostRequest)
{
$transaction=Yii::app()->db->beginTransaction();
try {
$providedIDs = $_POST['ids'];
$model = Contents::model();
if ( $model->deleteByPk($providedIDs) ) {
$index = 1;
$selectedIds = count($providedIDs);
foreach ($providedIDs as &$value) {
# Compile and submit multiple log messages
#return print_r ($model);
$logContent['content_id']=$value;
$logContent['user_id']=1;
/*This gives error >>*/ $logContent['description']= 'Content "'.$model->findByPk($value)->name.
'" (#'.$value.
') deleted by user "1" (#'.$logContent["user_id"].')';
if ( $this->dataLogger($logContent) ) {
if ( $index == $selectedIds )
$transaction->commit();
else
$index++;
}
}
#$transaction->commit();
echo CJSON::encode(array(
'status'=>'success',
'message'=>'Content(s) deleted! ',
));
exit;
}
}
catch(Exception $e) { // an exception is raised if a query fails
//something was really wrong - exception!
$transaction->rollBack();
//you should do sth with this exception (at least log it or show on page)
echo "ERROR: ". $e->getMessage();
#Yii::log( 'Exception when saving data: ' . $e->getMessage(), CLogger::LEVEL_ERROR );
}
}
else
{
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
}
As I learned from this thread: http://www.yiiframew…bypk-deleteall/ seems like deleteByPk() does not respect the transactional execution I have setup in my code (as it prepares and executes queries in its cycle). I am trying to achieve this with least amount of queries: 1) delete the selected rows, 2) write to a log table about the deletion. When I’m trying to get the name column of the rows that were deleted by “deletedByPk()”, that’s when it fires a PHP Error 8 about “Trying to get property of non-object…”
Do you have any ideas how to work around this? Besides running delete() inside my foreach statement…
Thank you in advance for your help