Dubby
Dubby

Reputation: 2402

How to use behaviors when operating as RESTful?

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/

Upvotes: 4

Views: 1987

Answers (1)

Joe Miller
Joe Miller

Reputation: 3893

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.

Upvotes: 8

Related Questions