Hi everyone i am implementing restful api in yii2
and having a conflict in ActionDelete
and ActionDeleteall
when i pass one parameter in url like http://localhost/yii2-api/api/modules/v1/countries/CD
it works fine and deletes the record CD
from database with DELETE
request. I dont know how can i pass multiple codes
in url so that it redirects to actionDeleteall
. Here is my controller
code.
class CountryController extends ActiveController
{
public $modelClass = 'api\modules\v1\models\Country';
public function actions()
{
$actions = parent::actions();
unset($actions['index']);
unset($actions['create']);
unset($actions['delete']);
unset($actions['update']);
unset($actions['view']);
return $actions;
}
public function actionDelete($id)
{
$model=$this->findModel($id);
if($model->delete())
{
$this->setHeader(200);
echo json_encode(array('status'=>1,'data'=>array_filter($model->attributes)),JSON_PRETTY_PRINT);
}
else
{
$this->setHeader(400);
echo json_encode(array('status'=>0,'error_code'=>400,'errors'=>$model->errors),JSON_PRETTY_PRINT);
}
}
public function actionDeleteall()
{
$ids=json_decode($_REQUEST['codes']);
$data=array();
foreach($ids as $id)
{
$model=$this->findModel($id);
if($model->delete())
$data[]=array_filter($model->attributes);
else
{
$this->setHeader(400);
echo json_encode(array('status'=>0,'error_code'=>400,'errors'=>$model->errors),JSON_PRETTY_PRINT);
return;
}
}
$this->setHeader(200);
echo json_encode(array('status'=>1,'data'=>$data),JSON_PRETTY_PRINT);
}
}
Here is my urlmanager
code
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country', // our country api rule,
'tokens' => [
'{id}' => '<id:\\w+>'
],
]
],
]
Let me know how can i override that action and access it with multiple codes
passed. Thank you
You could post an array of id values array and perform a loop
This is just a brief suggestion
obviuosly you should eval a proper error an resulting echo management
public function actionDelete($myArray)
{
foreach( $myArray as $key => $value){
$model=$this->findModel($value)
$model->delete();
}
}
If you have you array of id in
$myArray[0] = 'CD';
$myArray[1] = 'AA';
the url should be
http://localhost/yii2-api/api/horsebuzz/api/web/v1/countries/myArray=[27,28]
Or if you use code use actionDelete($code) ... ad so on
Or better if use UrlHelper
Url::to(['/countries/delete' , 'myArray' => [27,28] ]);
Url::to(['/countries/delete' , 'myArray' => $myArray ]);
first disable strict parsing in urlmanager
'enableStrictParsing' => false
then you can call your custom actions with any method the url will look like
http://localhost/yii2-api/api/web/v1/country/uraction
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.