forked from rafalkot/yii2-settings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSettingsForm.php
executable file
·90 lines (70 loc) · 2.2 KB
/
SettingsForm.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace rafalkot\yii2settings;
use yii\base\Exception;
use yii\base\Widget;
/**
* Settings form widget class.
*
* @package rafalkot\yii2settings
*/
class SettingsForm extends Widget
{
/**
* @var SettingsTrait Configured object
*/
public $object;
/**
* @var SettingsModel Helper dynamic model
*/
private $_model;
/**
* @var array Configuration array
*/
private $_formConfig = [];
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$config = $this->object->getSettingsFormConfig();
$this->_model = new SettingsModel(array_keys($config));
$this->_model->setAttributes($this->object->getSetting(), false);
foreach ($config as $key => $element) {
$element['input'] = isset($element['input']) ? $element['input'] : 'text';
if (in_array($element['input'], ['dropdown', 'checkboxList']) && empty($element['options'])
) {
throw new Exception('Input type ' . $element['input'] . ' requires `options` property');
}
if (!$this->_model->{$key} && isset($element['default'])) {
$this->_model->{$key} = $element['default'];
}
if (!isset($element['label'])) {
$config[$key]['label'] = $this->_model->generateAttributeLabel($key);
}
}
$this->_formConfig = $config;
}
/**
* @inheritdoc
*/
public function run()
{
$settings = \Yii::$app->request->post('Settings', []);
if (!empty($settings)) {
$this->_model->setAttributes($settings, false);
$this->object->setSetting($this->_model->getAttributes());
\Yii::$app->session->setFlash('settings', \Yii::t('yii2settings', 'Settings have been saved'));
}
if (\Yii::$app->request->isAjax) {
return $this->getView()->renderAjax('form', [
'model' => $this->_model,
'elements' => $this->_formConfig
], $this);
}
return $this->render('form', [
'model' => $this->_model,
'elements' => $this->_formConfig
]);
}
}