Reputation: 25699
When I delete a 'type' i set isActive = 0;
Every 'type' 'has many' 'causal'
So when disabling a type i want disable every causal
in type controller i'm trying this
$model = $this->loadModel($id);
$model->isActive = 0;
foreach ($model->causalsObj as $key => $causal ) {
$causal = CausalController::delete($causal->id);
}
$model->save();
This doesn't work (PHP error during ajax call)
Upvotes: 1
Views: 3227
Reputation: 4334
That should go into the model, not the controller, I'd use afterSave. so in the CasualType:
public function afterSave(){
if(!$this->isActive){
Casual::model()->deleteAll('type_id = '.$this->id);
}
return parent::afterSave();
}
If you don't actually mean 'delete' but deactivate you can still do this in one single query using CActiveRecord::updateAll:
public function afterSave(){
if(!$this->isActive){
Casual::model()->updateAll(array('isActive' => 0), 'type_id = '.$this->id);
}
return parent::afterSave();
}
Instantiating a controller in another controller does not make sense, controllers are there to handle user requests, not to hold your business logic
Upvotes: 5
Reputation: 1283
Do you have the following at the top of your code?
Yii::import('application.models.CausalController');
This should make it possible.
Also using SuVeRa's way to delete the items would be nicer:
foreach ($model->causalsObj as $key => $causal ) {
$causal->delete();
}
Or you can create a function in CausalController which deletes all causal's for a given id.
Upvotes: 0
Reputation: 5923
Looks like the problem is in your foreach loop, if you already have a relation set up you should be able to access it with $model->causal. If that doesn't work, check your relations are working correctly
$model = $this->loadModel($id);
$model->isActive = 0;
foreach ($model->causal as $item){
$item->delete();
}
$model->save();
Upvotes: 0