UpdateAction.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\rest;
  8. use Yii;
  9. use yii\base\Model;
  10. use yii\db\ActiveRecord;
  11. use yii\web\ServerErrorHttpException;
  12. /**
  13. * UpdateAction implements the API endpoint for updating a model.
  14. *
  15. * For more details and usage information on UpdateAction, see the [guide article on rest controllers](guide:rest-controllers).
  16. *
  17. * @author Qiang Xue <qiang.xue@gmail.com>
  18. * @since 2.0
  19. */
  20. class UpdateAction extends Action
  21. {
  22. /**
  23. * @var string the scenario to be assigned to the model before it is validated and updated.
  24. */
  25. public $scenario = Model::SCENARIO_DEFAULT;
  26. /**
  27. * Updates an existing model.
  28. * @param string $id the primary key of the model.
  29. * @return \yii\db\ActiveRecordInterface the model being updated
  30. * @throws ServerErrorHttpException if there is any error when updating the model
  31. */
  32. public function run($id)
  33. {
  34. /* @var $model ActiveRecord */
  35. $model = $this->findModel($id);
  36. if ($this->checkAccess) {
  37. call_user_func($this->checkAccess, $this->id, $model);
  38. }
  39. $model->scenario = $this->scenario;
  40. $model->load(Yii::$app->getRequest()->getBodyParams(), '');
  41. if ($model->save() === false && !$model->hasErrors()) {
  42. throw new ServerErrorHttpException('Failed to update the object for unknown reason.');
  43. }
  44. return $model;
  45. }
  46. }