Skip to content

Commit

Permalink
add EditAction
Browse files Browse the repository at this point in the history
  • Loading branch information
ZAYEC77 committed Aug 11, 2015
1 parent c5a88c1 commit 341b60e
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Allows save in integer field bit array.
Allows get lists from ActiveRecord.
### PasswordTrait
Easy work with password.
### EditAction
Action for AJAX record update.

## Installation
```bash
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"minimum-stability": "dev",
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": ">=2.0.0"
"yiisoft/yii2": ">=2.0.6"
},
"autoload": {
"psr-4": {
Expand Down
56 changes: 56 additions & 0 deletions src/EditAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace nullref\useful;

use Yii;
use yii\base\Action;
use yii\base\InvalidConfigException;
use yii\db\ActiveRecord;
use yii\web\NotFoundHttpException;

/**
* Action for AJAX record update
*/
class EditAction extends Action
{
/** @var callable */
public $findModel;

/** @var callable */
public $filter;

/**
* Check if action has valid findModel method
*/
public function init()
{
parent::init();
if (is_callable($this->findModel)){
throw new InvalidConfigException('findModel must be set');
}
}

/**
* Set new attribute value and save AR
* @throws NotFoundHttpException
*/
public function run()
{
if (!Yii::$app->request->isAjax) {
throw new NotFoundHttpException('The requested page does not exist.');
}
$post = Yii::$app->request->post();

if (!(empty($post['pk']) || empty($post['name']) || !isset($post['value']))) {
/** @var ActiveRecord $model */
$model = call_user_func($this->findModel, $post['pk']);
$attribute = $post['name'];
$value = $post['value'];
if (is_callable($this->filter)) {
$value = call_user_func($this->filter, $value, $attribute);
}
$model->$attribute = $value;
$model->save();
}
}
}

0 comments on commit 341b60e

Please sign in to comment.