-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFormBuilder.php
executable file
·127 lines (95 loc) · 2.7 KB
/
FormBuilder.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<?php
/**
* Created by PhpStorm.
* User: joels
* Date: 27/3/17
* Time: 9:34 AM
*/
namespace enigmatix\formbuilder;
use yii\base\Widget;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Inflector;
use yii\helpers\Json;
use yii\helpers\StringHelper;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
class FormBuilder extends Widget
{
protected $pluginDefaults = [
'dataType' => 'json',
'showActionButtons' => false,
'disableFields' => [
'header',
'paragraph',
'number',
'autocomplete',
'hidden',
'button']
];
var $pluginOptions = [];
var $saveButtonSelector = '.form-builder-save';
var $saveAction = 'post';
var $saveUrl;
var $fieldSelector;
var $saveMethod = 'ajax';
var $formId;
var $controller;
/**
* @var ActiveRecord
*/
var $model;
public function run() {
$this->registerAssets();
return Html::tag('div','',['id' => $this->id]);
}
protected function registerAssets(){
$view = $this->view;
$view->registerJs("window.{$this->getJsID()} = $('#$this->id').formBuilder({$this->getJavascriptOptions()});");
$view->registerJs($this->prepareSaveMethod());
FormBuilderAsset::register($view);
}
protected function getJavascriptOptions(){
return Json::encode(ArrayHelper::merge($this->pluginDefaults, $this->pluginOptions));
}
public function prepareSaveMethod(){
$selector = $this->saveButtonSelector;
$fieldSelector = $this->fieldSelector;
$saveAction = $this->saveAction;
$saveUrl = $this->saveUrl;
$formBuilderId = $this->id;
$method = $this->saveMethod;
$jsID = $this->getJsID();
$formId = $this->formId;
switch ($method){
case 'field':
return <<<JS
$('#{$formId}').on('beforeSubmit', function (e) {
$('{$fieldSelector}').attr('value', window.{$jsID}.formData);
return true;
});
JS;
break;
case 'ajax':
default:
return <<<JS
$("{$selector}").click(function() {
$.{$saveAction}('{$saveUrl}', window.{$jsID}.formData);
});
JS;
break;
}
}
public static function getValueList($values)
{
$return = [];
foreach ($values as $value){
$return[$value['value']] = $value['label'];
}
return $return;
}
protected function getJsID(){
return Inflector::camelize("yii2".$this->id."fb");
}
}