my controller code :
<?php
namespace app\controllers;
use Yii;
use yii\rest\ActiveController;
use yii\web\Response;
use app\models\submodels\SubPresensi;
use yii\filters\VerbFilter;
class PresensiApiController extends ActiveController
{
public $modelClass = 'app\models\submodels\Presensi';
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
// return [
// 'verbs' => ['class' => VerbFilter::className(),
// 'actions' => [
// 'index'=>['get'],
// 'view'=>['get'],
// 'create'=>['post'],
// 'update'=>['post'],
// 'delete' => ['delete'],
// 'deleteall'=>['post'],
// ],
// ]
// ], $behaviors;
}
private function setHeader($status) {
$status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
$content_type="application/json; charset=utf-8";
header($status_header);
header('Content-type: ' . $content_type);
header('X-Powered-By: ' . "Presensi Telkom Polban");
}
private function _getStatusCodeMessage($status) {
$codes = Array(
200 => 'OK',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
500 => 'Internal Server Error',
501 => 'Not Implemented',
);
return (isset($codes[$status])) ? $codes[$status] : '';
// return $codes[$status];
}
public function actionCreatePresensi($nim,$idjadwalmatkul) {
date_default_timezone_set("Asia/Jakarta");
// $params=$_REQUEST;
$params = Yii::$app->request->post();
$model = new SubPresensi();
$model->attributes=$params;
$model->NIM = $nim;
$model->Id_Jadwal_Matkul = $idjadwalmatkul;
$model->Waktu_Presensi = date('Y-m-d H:i:s');
$model->save();
if ($model->save()) {
// $this->setHeader(200);
echo json_encode(array('status'=>1,'data'=>array_filter($model->attributes)));
}
else {
$this->setHeader(400);
echo json_encode(array('status'=>0,'error_code'=>400,'errors'=>$model->errors),JSON_PRETTY_PRINT);
}
}
}