UEditor.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace common\widgets\editor\ueditor;
  3. use Yii;
  4. use yii\helpers\ArrayHelper;
  5. use yii\helpers\Html;
  6. use yii\helpers\Json;
  7. use yii\helpers\Url;
  8. use yii\web\View;
  9. use yii\widgets\InputWidget;
  10. class UEditor extends InputWidget
  11. {
  12. //配置选项,参阅Ueditor官网文档(定制菜单等)
  13. public $clientOptions = [];
  14. //默认配置
  15. protected $_options;
  16. public $saveUrl = [];
  17. /**
  18. * @throws \yii\base\InvalidConfigException
  19. */
  20. public function init()
  21. {
  22. if (isset($this->options['id'])) {
  23. $this->id = $this->options['id'];
  24. } else {
  25. $this->id = $this->hasModel() ? Html::getInputId($this->model,
  26. $this->attribute) : $this->id;
  27. }
  28. $this->_options = [
  29. 'serverUrl' => Url::to($this->saveUrl),
  30. 'initialFrameWidth' => '100%',
  31. 'initialFrameHeight' => '400',
  32. 'lang' => (strtolower(Yii::$app->language) == 'en-us') ? 'en' : 'zh-cn',
  33. ];
  34. $this->clientOptions = ArrayHelper::merge($this->_options, $this->clientOptions);
  35. parent::init();
  36. }
  37. public function run()
  38. {
  39. $this->registerClientScript();
  40. if ($this->hasModel()) {
  41. return Html::activeTextarea($this->model, $this->attribute, ['id' => $this->id]);
  42. } else {
  43. return Html::textarea($this->id, $this->value, ['id' => $this->id]);
  44. }
  45. }
  46. /**
  47. * 注册客户端脚本
  48. */
  49. protected function registerClientScript()
  50. {
  51. UEditorAsset::register($this->view);
  52. $clientOptions = Json::encode($this->clientOptions);
  53. $script = "UE.getEditor('" . $this->id . "', " . $clientOptions . ");";
  54. $this->view->registerJs($script, View::POS_READY);
  55. }
  56. }