1 <?php
2 3 4 5 6 7 8 9
10
11 12 13 14 15 16 17 18 19 20
21 class JSONEditorView extends CWidget
22 {
23 24 25
26 public $htmlOptions;
27
28 29 30
31 public $rootNodeName;
32
33 34 35
36 public $data;
37
38 39 40 41 42 43
44 public $cssFile;
45
46 47 48
49 public $inputButtonLabel = 'Switch to text input';
50
51 52 53
54 public $initButtonLabel = 'Switch to JSON editor';
55
56 57 58
59 public $submitButtonLabel = 'Save';
60
61 public function init()
62 {
63 if(isset($this->htmlOptions['id']))
64 $id=$this->htmlOptions['id'];
65 else
66 $id=$this->htmlOptions['id']=$this->getId();
67
68 if(!isset($this->htmlOptions['style']))
69 $this->htmlOptions['style'] = 'border:solid 2px #88F; width:100%;';
70
71 if($this->rootNodeName === null)
72 $this->rootNodeName = 'root';
73
74 if($this->data === null)
75 $this->data = '{}';
76
77 $cs=Yii::app()->getClientScript();
78
79 $url = Yii::app()->getAssetManager()->publish(dirname(__FILE__).DIRECTORY_SEPARATOR.'lib');
80
81 $cs->registerScriptFile($url.'/jquery.json-2.2.min.js');
82 $cs->registerScriptFile($url.'/jquery.jsoneditor.js');
83
84 if($this->cssFile===null)
85 $cs->registerCssFile($url.'/jsoneditor.css');
86 else if($this->cssFile!==false)
87 $cs->registerCssFile($this->cssFile);
88
89 $cs->registerScript(
90 'JSONEditorView#'.$id,
91 "jQuery(\"#{$id}\").jsoneditor('init', {root:'{$this->rootNodeName}', data:{$this->data}});"
92 );
93
94 $cs->registerScript(
95 'JSONEditorView-submit#'.$id,
96 "
97 jQuery(\"#{$id}-form\").submit(function(){
98 var obj = jQuery(\"#{$id}\");
99
100 obj.jsoneditor('input');
101 obj.children('textarea').attr('name', '{$id}-json');
102 });
103 "
104 );
105 }
106
107 public function run()
108 {
109 echo CHtml::beginForm('', 'post', array(
110 'id'=>$this->htmlOptions['id'].'-form',
111 ));
112 echo CHtml::button($this->inputButtonLabel, array(
113 'onclick'=>"jQuery(\"#{$this->htmlOptions['id']}\").jsoneditor('input')"
114 ));
115 echo CHtml::button($this->initButtonLabel, array(
116 'onclick'=>"jQuery(\"#{$this->htmlOptions['id']}\").jsoneditor('init')"
117 ));
118 echo CHtml::submitButton($this->submitButtonLabel, array(
119 'name'=>$this->htmlOptions['id'].'-save'
120 ));
121 echo CHtml::tag('div', $this->htmlOptions);
122 echo CHtml::hiddenField($this->htmlOptions['id'].'-json', '', array());
123 echo CHtml::endForm();
124 }
125 }
126