spencer4of6 spencer4of6 - 3 months ago 14
reST (reStructuredText) Question

Yii2 REST create with fields()

Let's say that I had the following API set up:

Controller:

<?php
namespace app\modules\v1\controllers;

use yii;

class ResourceController extends \yii\rest\ActiveController
{
public $modelClass = 'app\modules\v1\models\Resource';
}


Model:


use yii;

class Resource extends \yii\db\ActiveRecord
{

public static function tableName()
{
return 'ResourceTable';
}

public function fields()
{
return [
'id' => 'ResourceID',
'title' => 'ResourceTitle',
];
}
}


where my table only has the two columns,
ResourceID
and
Title
.

When I try a
GET
request on the API, it works fine and returns the list of resources (or single resource in the case of
resource/{id}
) with the aliased field names. But when I try to
POST
to create a resource, I want to use the aliased field names (e.g.
title
instead of
ResourceTitle
). The problem is that the default
CreateAction
supplied by Yii does
$model->load()
, which looks for the field names in the table. If I use the aliased names then it returns an error. If I use the table field names, it works fine.

So my question is, is there a way to expose resource attributes to the end user where the field names (using the
fields()
function) are the same for reading and creating? If possible, I'd like to avoid writing my own CreateAction.

Answer

You can create getters/setters for alias.

public function getTitle(){ return $this->ResourceTitle; }
public function setTitle($val){ $this->ResourceTitle = $val ; }
Comments