Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use behaviors when operating as RESTful?

Tags:

rest

yii

yii2

I am following the instructions* on how to create a RESTful service with Yii2 but the behavior method causes the error:

Response content must not be an array.

If I remove the behavior method then I receive the JSON response that I expect. I tried removing the behavior method after reading another post**.

However I am a little unfamiliar with behaviors. Can we not use behaviors with Yii2 with REST or is this a bug? I would be very appreciate if someone could shed some light on this.

*http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html **http://www.yiiframework.com/forum/index.php/topic/60432-rest-api-failing-with-behaviours/

like image 456
Dubby Avatar asked Feb 10 '23 20:02

Dubby


1 Answers

Your problem is that you have overridden the behaviors() method completely. The parent classes have behaviors attached that negotiate the content headers and response format. To get round this your behaviors needs to return an array merged with the parent behaviors. So your behaviors() method will look like this;

public function behaviors() {
    return ArrayHelper::merge(parent::behaviors(), [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['post'],
                    ],
                ],
    ]);
}

You need to remember to add use yii\helpers\ArrayHelper at the top of the controller class.

like image 198
Joe Miller Avatar answered Feb 13 '23 08:02

Joe Miller