Skip to content

Commit 341b60e

Browse files
committed
add EditAction
1 parent c5a88c1 commit 341b60e

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ Allows save in integer field bit array.
1212
Allows get lists from ActiveRecord.
1313
### PasswordTrait
1414
Easy work with password.
15+
### EditAction
16+
Action for AJAX record update.
1517

1618
## Installation
1719
```bash

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
"minimum-stability": "dev",
2929
"require": {
3030
"php": ">=5.4.0",
31-
"yiisoft/yii2": ">=2.0.0"
31+
"yiisoft/yii2": ">=2.0.6"
3232
},
3333
"autoload": {
3434
"psr-4": {

src/EditAction.php

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
namespace nullref\useful;
4+
5+
use Yii;
6+
use yii\base\Action;
7+
use yii\base\InvalidConfigException;
8+
use yii\db\ActiveRecord;
9+
use yii\web\NotFoundHttpException;
10+
11+
/**
12+
* Action for AJAX record update
13+
*/
14+
class EditAction extends Action
15+
{
16+
/** @var callable */
17+
public $findModel;
18+
19+
/** @var callable */
20+
public $filter;
21+
22+
/**
23+
* Check if action has valid findModel method
24+
*/
25+
public function init()
26+
{
27+
parent::init();
28+
if (is_callable($this->findModel)){
29+
throw new InvalidConfigException('findModel must be set');
30+
}
31+
}
32+
33+
/**
34+
* Set new attribute value and save AR
35+
* @throws NotFoundHttpException
36+
*/
37+
public function run()
38+
{
39+
if (!Yii::$app->request->isAjax) {
40+
throw new NotFoundHttpException('The requested page does not exist.');
41+
}
42+
$post = Yii::$app->request->post();
43+
44+
if (!(empty($post['pk']) || empty($post['name']) || !isset($post['value']))) {
45+
/** @var ActiveRecord $model */
46+
$model = call_user_func($this->findModel, $post['pk']);
47+
$attribute = $post['name'];
48+
$value = $post['value'];
49+
if (is_callable($this->filter)) {
50+
$value = call_user_func($this->filter, $value, $attribute);
51+
}
52+
$model->$attribute = $value;
53+
$model->save();
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)