Reputation: 11
How to check input data in YII2 for REST API?
Here's how it's done in a non-REST API:
Controller
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\Index__GET;
class SiteController extends Controller
{
public function actionIndex($ch_name_url = null)
{
$model = new Index__GET();
$model->ch_name_url = $ch_name_url;
if($model->validate()){
return $this->render('index');
}
}
}
Model
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class Index__GET extends Model
{
public $ch_name_url;
public function rules()
{
return [
['ch_name_url', 'trim'],
['ch_name_url', 'required'],
];
}
}
And now in the controller call $model->validate()
for data validation. How to do validation incoming data in the REST API, using yii\rest\Controller
and yii\rest\ActiveController
?
I try but data validation fails:
I want a GET request to include two required fields.
But if I use /users/123
I will receive data, while I should not receive it, because of the model [['id', 'ch_name_url'], 'required'],
.
Me need /users?id=123&ch_name_url=myname
Controller
namespace app\controllers;
use yii\rest\ActiveController;
class IndexController extends ActiveController
{
public $modelClass = 'app\models\Index__GET';
}
Model
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class Index__GET extends ActiveRecord
{
public $id;
public $ch_name_url;
public $email;
public static function tableName()
{
return 'user';
}
public function fields()
{
return ['id', 'ch_name_url', 'email'];
}
public function rules()
{
return [
[['id', 'ch_name_url'], 'required'],
];
}
}
Upvotes: 1
Views: 1064
Reputation: 499
Just create a controller extending from \yii\rest\ActiveController
, then validate
will run automatically. Do something like this:
namespace app\controllers;
use yii\rest\ActiveController;
class IndexController extends ActiveController
{
public $modelClass = 'app\models\Index__GET';
}
$model->validate()
is called by default when you call $model->save()
, but if you need to validate a model in an action, do it like you did on your question example code.
Just remember that the actions from REST are used a bit different from normal call, where actionIndex
usually is not needed.
For more information, follow the original docs: REST Quick Start
Upvotes: 0