Reputation: 5319
I am creating an API in yii2, all methods are working fine beside of put
method. I am getting data in before_save
method but getting below error when it save.
{ "name": "Internal Server Error", "message": "Failed to update the object for unknown reason.", "code": 0, "status": 500,
"type": "yii\web\ServerErrorHttpException" }
here is my controller file
ProductsController.php
<?php
namespace app\controllers;
use yii\rest\ActiveController;
use yii\filters\auth\HttpBearerAuth;
class ProductsController extends ActiveController {
public $modelClass = 'app\models\Product';
public function __construct($id, $module, $config = array()) {
parent::__construct($id, $module, $config);
}
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
];
return $behaviors;
}
}
Here is model file Product.php
<?php
namespace app\models;
use yii\db\ActiveRecord;
use yii;
class Product extends ActiveRecord {
public static function tableName() {
return '{{%o2o_products}}';
}
public function rules() {
return [
[['name'], 'required'],
];
}
}
And this is my web.php
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
'<alias:index|about|contact|login>' => 'site/<alias>',
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
['class' => 'yii\rest\UrlRule', 'controller' => 'products'],
['class' => 'yii\rest\UrlRule', 'controller' => 'orders'],
],
]
I tried with removing rule
with on create and on update statements. but no success.
Let me know if you need any thing else.
Upvotes: 0
Views: 1192
Reputation: 5501
I was facing same issue recently and the solution is data is not passing properly. Normally it should pass as a json.
namespace app\controllers;
use yii\rest\ActiveController;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\helpers\ArrayHelper;
class ProductsController extends ActiveController {
public $modelClass = 'app\models\Product';
public function __construct($id, $module, $config = array()) {
parent::__construct($id, $module, $config);
}
public function behaviors() {
return ArrayHelper::merge(parent::behaviors(), [
[
'class' => HttpBearerAuth::className(),
'only' => ['index', 'view', 'create', 'update', 'search'],
// 'formats' => ['application/json' => Response::FORMAT_JSON,],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index' => ['get'],
'view' => ['get'],
'create' => ['post'],
'update' => ['PUT'],
'delete' => ['delete'],
'deleteall' => ['post'],
'search' => ['get']
],
]
]);
}
Try with passing data in json
{
"name": "product name"
}
Upvotes: 0