And when I press delete button, this error appears:
Error 400: Your request is invalid
My TvPactivosMedicamentosController.php is:
<?php
class TvPactivosMedicamentosController extends Controller
{
public function actionDelete($IdMedicamento, $IdPrincipioActivo)
{
TvPactivosMedicamentos::model()->deleteByPk(
array(
'IdMedicamento'=>$IdMedicamento,
'IdPrincipio_Activo'=>$IdPrincipioActivo,
));
// 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('update'));
}
}
This same thing happens with other AJAX functions. What is the problem?
But it doesn’t delete data.
controller code
public function actionDelete($IdMedicamento, $IdPrincipioActivo)
{
$this->loadModel($IdMedicamento, $IdPrincipioActivo)->delete();
// 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('update'));
}
public function loadModel($IdMedicamento, $IdPrincipio_Activo)
{
$model=ToUnidades::model()->findByPk($IdMedicamento, $IdPrincipio_Activo);
if($model===null)
throw new CHttpException(404,'A páxina solicitada non existe.');
return $model;
}
you can also do like table level deletion when the parent row gets deleted… you can use ON DELETE CASCATE to delete composite key entry automatically with parent record.
Yii Framework Class Reference says in findByPk() method for CActiveRecord:
public CActiveRecord findByPk(mixed $pk, mixed $condition='', array $params=array ( ))
Where mixed $pk is : "primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value)."
[size="4"][b]
ARRAY!!!!![/b][/size]
Then, in my controller:
public function loadModel($IdPrincipio_Activo, $IdMedicamento)
{
$model=TvPactivosMedicamentos::model()->findByPk(
array(
'IdPrincipio_Activo'=>$IdPrincipio_Activo,
'IdMedicamento'=>$IdMedicamento)
);
if($model===null)
throw new CHttpException(404,'A páxina solicitada non existe.');
return $model;
}
public function primaryKey()
{
return array('firstField', 'secondField', 'thirdField');
}
Controller:
public function actionDelete(array $id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request & check if $id is an array
if(is_array($id))
{
if($this->loadModel($id)->delete())
{
$this->redirect($_SERVER['HTTP_REFERER']);
}
}
else
throw new CHttpException(400,'ID is not an array.');
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}