Задать вопрос
@teodor7teodor7

Как исправить ошибку Yii2 Rest при приобращении put, post добовляет null?

При отправки через postman при использование put, post запросов записывается null.
{
    "id": 242,
    "status": null,
    "name": null,
    "short_name": null,
    "edit": 242,
    "delete": 242
}

Модель
<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
class Mestype extends ActiveRecord  {
 
  public static function tableName() {
    return 'list_mestype';
  }
  
    public function fields() {
    return [
      'id', 'status', 'name', 'short_name',
      'edit' => function () {
      return $this->id;}, 
      'delete' => function () {
      return $this->id;}        
  
    ];
  }
  
 
  
  public static function getMestypesList()
  {
    // Выбираем только те категории, у которых есть дочерние категории
    $mestypes = Mestypes::find()
        ->select(['id', 'short_name'])
        ->distinct(true)
        ->all();
 
    return ArrayHelper::map($mestypes, 'id', 'short_name');
  }
}

Контролер
<?php

namespace app\controllers;

use yii\rest\ActiveController;
use app\models\Mestypes;

/**
 * UserController implements the CRUD actions for User model.
 */
class MestypeController extends ActiveController {

  public $modelClass = 'app\models\Mestype';

  public function behaviors() {
    return [
      [
        'class' => \yii\filters\ContentNegotiator::className(),
        'only' => ['index', 'view', 'create', 'update'],
        'formats' => [
          'application/json' => \yii\web\Response::FORMAT_JSON,
        ],
      ],
    ];
  }

  public function actions() {
    $actions = parent::actions();
    unset($actions['index']);
 
    return $actions;
  }

  public function actionIndex() {
    $query = Mestypes::find();
    $start = (int) \Yii::$app->request->get('start') ? (int) \Yii::$app->request->get('start') : 0;
    $limit = (int) \Yii::$app->request->get('length') ? (int) \Yii::$app->request->get('length') : 10;
    $search = \Yii::$app->request->get('search')['value'];
    $order = \Yii::$app->request->get('order');
    $order[0]['dir']= ($order[0]['dir'] == "asc") ? SORT_ASC : SORT_DESC;
//    $role =  (int) \Yii::$app->request->get('role');
//
//    $pagination = new Pagination([
//       'totalCount' => $query->where(['role' => $role])->count(),
//     ]);

    if (!empty($search)) {
      $cost['data'] = $query
          ->where(['like', 'name', $search])
          ->orWhere(['like', 'short_name', $search])->orderBy(['id' => $order[0]['dir']])
          ->offset($start)->limit($limit)->all();
    } else {
      $cost['data'] = $query->orderBy(['id' => $order[0]['dir']])->offset($start)->limit($limit)->all();
    }

    $cost['recordsTotal'] = $query->count(); //$pagination->totalCount;
    $cost['recordsFiltered'] = $query->count(); //$pagination->totalCount;
    return $cost;
  }
  
  
 
}


web.php
<?php

$params = require(__DIR__ . '/params.php');

$config = [
  'id' => 'basic',
  'basePath' => dirname(__DIR__),
  'bootstrap' => ['log'],
  'components' => [

    'assetManager' => [
//      'bundles' => [
//        'yii\web\JqueryAsset' => [
//          'js' => []
//        ],
//      ]


//  'bundles' => array(
//    'yii\web\JqueryAsset' => array(
//        'sourcePath' => null,
//        'js' => array(
//             '//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js',
//        ),
//    ),
//)      
    ],
   
    'user' => [
      'identityClass' => 'app\models\User',
      'enableAutoLogin' => true,
    ],
    'cache' => [
      'class' => 'yii\caching\FileCache',
    ],
    'errorHandler' => [
      'errorAction' => 'site/error',
    ],
    'mailer' => [
      'class' => 'yii\swiftmailer\Mailer',
      // send all mails to a file by default. You have to set
      // 'useFileTransport' to false and configure a transport
      // for the mailer to send real emails.
      'useFileTransport' => true,
    ],
    'urlManager' => [

      'enablePrettyUrl' => true,
      'showScriptName' => false,
      'enableStrictParsing' => true,
      'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => 'users'],
        ['class' => 'yii\rest\UrlRule', 'controller' => 'costs'],
        ['class' => 'yii\rest\UrlRule', 'controller' => 'mestype'],
        ['class' => 'yii\rest\UrlRule', 'controller' => 'products'],
        '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
        '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
      ],
       
    ],
     'request' => [
      // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
      'cookieValidationKey' => 'tb2R4PTTndJoNRjQjdefm5crrM6GfYsz',
      'parsers' => [ 'application/json' => 'yii\web\JsonParser' ],
      'baseUrl' => '',
    ],
    'security' => [
      'passwordHashStrategy' => 'pasword_hash'
    ],
    'log' => [
      'traceLevel' => YII_DEBUG ? 3 : 0,
      'targets' => [
        [
          'class' => 'yii\log\FileTarget',
          'levels' => ['error', 'warning'],
        ],
      ],
    ],
    'db' => require(__DIR__ . '/db.php'),
  /*
    'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
    ],
    ],
   */
  ],
  'params' => $params,
];

if (YII_ENV_DEV) {
  // configuration adjustments for 'dev' environment
  $config['bootstrap'][] = 'debug';
  $config['modules']['debug'] = [
    'class' => 'yii\debug\Module',
  ];

  $config['bootstrap'][] = 'gii';
  $config['modules']['gii'] = [
    'class' => 'yii\gii\Module',
  ];
}

return $config;


помогите решить проблему.
  • Вопрос задан
  • 1414 просмотров
Подписаться 1 Оценить 3 комментария
Пригласить эксперта
Ответы на вопрос 1
vyachin
@vyachin
Ищу работу
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы