YaakovHatam
YaakovHatam

Reputation: 2344

Yii2 ActiveController rewrite default post action

I have no clue how to do it in YII2 and I didn't find anything in the docs. I've tried:

public function actionCreate() {
     //code   
}

my controller:

<?php
namespace app\controllers;

use yii\filters\auth\HttpBasicAuth;
use yii\rest\ActiveController;

class TempController extends ActiveController
{
    public $modelClass = 'app\models\Event';

}
?>

How to rewrite default post action in a Yii2 ActiveController?

Upvotes: 0

Views: 470

Answers (1)

Bizley
Bizley

Reputation: 18021

I assume by default post action you mean create action with POST HTTP method.

You need to override actions() method in TempController.

You can remove it:

/**
 * @inheritdoc
 */
public function actions()
{
    $defaultActions = parent::actions();
    unset($defaultActions['create']);
    return $defaultActions;
}

And now you can write your own actionCreate method like you tried before.

Or you can create separate action class and use it instead:

/**
 * @inheritdoc
 */
public function actions()
{
    $defaultActions = parent::actions();
    $defaultActions['create'] = [
        'class' => 'yii\rest\CreateAction', // change it to your class
        // modify configuration below, or not
        'modelClass' => $this->modelClass,
        'checkAccess' => [$this, 'checkAccess'],
        'scenario' => $this->createScenario,
    ];
    return $defaultActions;
}

Upvotes: 1

Related Questions