Esempio n. 1
1
    function run()
    {
        parent::run();
        $wid = $this->options['id'];
        echo Html::activeHiddenInput($this->model, $this->attribute);
        echo Html::beginTag('div', ['id' => $wid . '-buttons', 'class' => 'input-group btn-group']);
        $items = PublishBehavior::getPublishedOptions();
        $colors = PublishBehavior::getPublishedColors();
        foreach ($items as $key => $item) {
            echo Html::button($item, ['data' => ['value' => $key], 'class' => $key == $this->model->{$this->attribute} ? 'btn btn-' . $colors[$key] . ' active' : 'btn btn-default']);
        }
        echo Html::endTag('div');
        $js_colors = Json::encode($colors);
        $js = <<<JS
 \$('#{$wid}-buttons').find('button').each(function(){
   \$(this).on('click',function(){
     \$('#{$wid}-buttons').find('button').each(function(){
        \$(this).removeClass('btn-danger btn-warning btn-success btn-info active');
        \$(this).addClass('btn-default');
     });
     var color={$js_colors};
     \$(this).removeClass('btn-default');
     \$(this).addClass('btn-'+color[\$(this).data('value')]+' active');
     \$('#{$wid}').val(\$(this).data('value'))
   });  
});               
JS;
        $this->view->registerJs($js);
    }
Esempio n. 2
0
 /**
  * Register widget client scripts.
  */
 protected function registerClientScript()
 {
     $view = $this->getView();
     $options = Json::encode($this->jsOptions);
     Asset::register($view);
     $view->registerJs('jQuery.comment(' . $options . ');');
 }
Esempio n. 3
0
    public function run()
    {
        //Если данные по доставке закешированы просто рисуем их иначе делаем ajax запрос, чтобы заполнился кеш
        if (\Yii::$app->v3toysSettings->isCurrentShippingCache) {
            return $this->render($this->viewFile);
        } else {
            $js = \yii\helpers\Json::encode(['backend' => \yii\helpers\Url::to('/v3toys/cart/get-current-shipping')]);
            $this->view->registerJs(<<<JS
    (function(sx, \$, _)
    {
        sx.classes.GetShipping = sx.classes.Component.extend({

            _onDomReady: function()
            {
                var self = this;

                _.delay(function()
                {
                    sx.ajax.preparePostQuery(self.get('backend')).execute();
                }, 500);
            }
        });

        new sx.classes.GetShipping({$js});

    })(sx, sx.\$, sx._);
JS
);
        }
    }
 public function run($id)
 {
     $model = $this->getNodeById($id);
     $model->scenario = 'move';
     $model->load(Yii::$app->request->post(), '');
     if (!$model->validate()) {
         throw new HttpException(500, current(current($model->getErrors())));
     }
     if (!$model->relatedNode instanceof $this->treeModelName) {
         throw new NotFoundHttpException(Yii::t('gtreetable', 'Position indicated by related ID is not exists!'));
     }
     try {
         if (is_callable($this->beforeAction)) {
             call_user_func_array($this->beforeAction, ['model' => $model]);
         }
         $action = $this->getMoveAction($model);
         if (!call_user_func(array($model, $action), $model->relatedNode)) {
             throw new Exception(Yii::t('gtreetable', 'Moving operation `{name}` failed!', ['{name}' => Html::encode((string) $model)]));
         }
         if (is_callable($this->afterAction)) {
             call_user_func_array($this->afterAction, ['model' => $model]);
         }
         echo Json::encode(['id' => $model->getPrimaryKey(), 'name' => $model->getName(), 'level' => $model->getLevel(), 'type' => $model->getType()]);
     } catch (\Exception $e) {
         throw new HttpException(500, $e->getMessage());
     }
 }
 public function up()
 {
     mb_internal_encoding("UTF-8");
     $tableOptions = $this->db->driverName === 'mysql' ? 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB' : null;
     $this->createTable('{{%wysiwyg}}', ['id' => Schema::primaryKey(), 'name' => Schema::string()->notNull(), 'class_name' => Schema::string()->notNull(), 'params' => Schema::text(), 'configuration_model' => Schema::string()], $tableOptions);
     $this->insert('{{%wysiwyg}}', ['name' => 'Imperavi', 'class_name' => 'vova07\\imperavi\\Widget', 'params' => Json::encode(['settings' => ['replaceDivs' => false, 'minHeight' => 200, 'paragraphize' => false, 'pastePlainText' => true, 'buttonSource' => true, 'imageManagerJson' => Url::to(['/backend/dashboard/imperavi-images-get']), 'plugins' => ['table', 'fontsize', 'fontfamily', 'fontcolor', 'video', 'imagemanager'], 'replaceStyles' => [], 'replaceTags' => [], 'deniedTags' => [], 'removeEmpty' => [], 'imageUpload' => Url::to(['/backend/dashboard/imperavi-image-upload'])]]), 'configuration_model' => 'app\\modules\\core\\models\\WysiwygConfiguration\\Imperavi']);
 }
Esempio n. 6
0
 public function actionNotify($id)
 {
     $response = ['result' => 'false', 'returnCode' => '500', 'message' => '失败'];
     $express = Express::findOne($id);
     if ($express && isset($_POST['param'])) {
         $param = Json::decode($_POST['param']);
         if (isset($param['lastResult']) && $express->company == $param['lastResult']['com'] && $express->number == $param['lastResult']['nu'] && (empty($express->auth_key) || isset($_POST['sign']) && $this->module->manager->verify($_POST['sign'], $_POST['param'], $express->auth_key))) {
             $express->status = $this->module->manager->getStatus($param['lastResult']['state']);
             $express->details = Json::encode($param['lastResult']['data']);
             if ($param['lastResult']['ischeck'] == 1 && $param['lastResult']['state'] == 3) {
                 $express->receipted_at = strtotime($param['lastResult']['data'][0]['time']);
             }
             if ($express->save()) {
                 $response['result'] = 'true';
                 $response['returnCode'] = '200';
                 $response['message'] = '成功';
                 if ($notifyClass = $this->module->notifyClass) {
                     $notifyClass::receipted($id);
                 }
             }
         }
     }
     \Yii::$app->response->format = 'json';
     return $response;
 }
Esempio n. 7
0
 /**
  * Return plugin options in json format
  * @return string
  */
 public function getPluginOptions()
 {
     if (!isset($this->pluginOptions['type'])) {
         $this->pluginOptions['type'] = $this->type;
     }
     return Json::encode($this->pluginOptions);
 }
 protected function registerJs($selector, $options, $callback)
 {
     $view = $this->getView();
     DateRangePickerAsset::register($view);
     $js = '$("' . $selector . '").daterangepicker(' . Json::encode($options) . ($callback ? ', ' . Json::encode($callback) : '') . ');';
     $view->registerJs($js, View::POS_READY);
 }
 public function actionAjaxGet()
 {
     $page = (int) \Yii::$app->request->get('page', 1);
     $pageSize = (int) \Yii::$app->request->get('rows', 20);
     $result = (new FriendLink())->getDataByPage($page, $pageSize);
     exit(Json::encode($result));
 }
Esempio n. 10
0
 protected function registerAssets()
 {
     ClockPickerAsset::register($this->view);
     $inputId = "#{$this->options['id']}";
     $pluginOptions = !empty($this->pluginOptions) ? Json::encode($this->pluginOptions) : '{}';
     $this->view->registerJs("jQuery('{$inputId}').clockpicker({$pluginOptions});");
 }
Esempio n. 11
0
 public function run()
 {
     $this->defaultLabel = Yii::t('app', $this->defaultLabel);
     self::$count++;
     if ($this->id === null) {
         $this->id = 'multi-select-' . self::$count;
     }
     if ($this->name === null) {
         $this->name = $this->model->formName() . '[' . $this->attribute . '][]';
     }
     $list = [$this->defaultIndex => $this->defaultLabel] + $this->items;
     $table = $this->getSelectedItems($this->items);
     $params = ['list' => $list, 'table' => $table, 'label' => $this->label, 'id' => $this->id, 'name' => $this->name, 'ajax' => $this->ajax, 'sortable' => $this->sortable];
     $view = $this->getView();
     // @todo
     // $errorFunction =
     $json = \yii\helpers\Json::encode(['addUrl' => $this->addUrl, 'ajax' => $this->ajax, 'defaultIndex' => $this->defaultIndex, 'removeUrl' => $this->removeUrl, 'selectedItems' => $this->selectedItems, 'ajaxData' => $this->ajaxData, 'errorFunction' => new JsExpression($this->errorFunction), 'successFunction' => new JsExpression($this->successFunction)]);
     if (self::$count == 1) {
         $view = $this->getView();
         JuiAsset::register($view);
         $view->registerJs("jQuery.fn.multiSelect = function(params){\n                var \$multiSelect = \$(this);\n                for(var key in params.selectedItems){\n                    \$multiSelect.find('select.list option[value=\"' + params.selectedItems[key] + '\"]').eq(0).addClass('hidden');\n                }\n                \$multiSelect.on('click', 'table a.remove', function(){\n                    \$this = \$(this);\n                    var \$tr = \$this.parents('tr').eq(0);\n                    var \$td = \$tr.find('td').eq(0);\n                    if(params.ajax){\n                        var data = params.ajaxData;\n                        data.id = \$tr.attr('data-id');\n                        \$.ajax({\n                            'data' : data,\n                            'dataType' : 'json',\n                            'success' : function(data){\n                                if(data.status == 1){\n                                    \$multiSelect.find('select.list').find('option[value=\"' + \$tr.attr('data-id') + '\"]').removeClass('hidden');\n                                    \$tr.remove();\n                                    params.successFunction(data);\n                                }else{\n                                    params.errorFunction(data);\n                                }\n                            },\n                            'type' : 'get',\n                            'url' : params.removeUrl\n                        });\n                    }else{\n                        \$multiSelect.find('select.hidden').find('option[value=\"' + \$tr.attr('data-id') + '\"]').remove();\n                        \$tr.remove();\n                        \$multiSelect.find('select.list').find('option[value=\"' + \$tr.attr('data-id') + '\"]').removeClass('hidden');\n                    }\n                    return false;\n                }).on('change', 'select', function(){\n                    var \$this= \$(this);\n                    if(\$this.val() != params.defaultIndex){\n                        var \$item = \$this.find('option[value=\"' + \$this.val() + '\"]');\n                        var \$table = \$multiSelect.find('table').eq(0);\n                        var \$clone = \$table.find('tr.hidden').eq(0).clone().removeClass('hidden').attr('data-id', \$this.val());\n                        \$clone.find('td').eq(0).text(\$item.text());\n                        \$input = \$('<input type=hidden>').val(\$this.val()).attr(\"name\", \"" . $this->name . "\");\n                        \$clone.append(\$input);\n                        if(params.ajax){\n                            var data = params.ajaxData;\n                            data.id = \$this.val();\n                            \$.ajax({\n                                'data' : data,\n                                'dataType' : 'json',\n                                'success' : function(data){\n                                    if(data.status == 1){\n                                        \$item.addClass('hidden');\n                                        \$clone.appendTo(\$table);\n                                        \$this.find('option[value=\"' + params.defaultIndex + '\"]').attr('selected', 'selected');\n                                        params.successFunction(data);\n                                    }else{\n                                        params.errorFunction(data);\n                                    }\n                                },\n                                'tyte' : 'get',\n                                'url' : params.addUrl\n                            });\n                        }else{\n                            \$('<option></option>').attr('value', \$this.val()).attr('selected', 'selected').text(\$item.text()).appendTo(\$multiSelect.find('select.hidden').eq(0));\n                            \$item.addClass('hidden');\n                            \$clone.appendTo(\$table);\n                        }\n                    }\n                });\n                }", View::POS_END);
     }
     $view->registerJs("jQuery('#" . $this->id . "').multiSelect(" . $json . ");");
     if ($this->sortable) {
         $view->registerJs("jQuery('#" . $this->id . " table tbody').sortable({placeholder: \"ui-state-highlight\"});");
     }
     echo $this->render('multiSelect', $params);
 }
Esempio n. 12
0
 /**
  * @param bool $returnJson
  * @return bool|string
  */
 public function save($returnJson = true)
 {
     $primaryKeys = $this->model->primaryKey();
     $primaryKey = $primaryKeys[0];
     $operation = \Yii::$app->getRequest()->post($this->oper);
     if ($operation == 'edit') {
         $id = \Yii::$app->getRequest()->post($primaryKey);
         if (empty($id)) {
             $id = \Yii::$app->getRequest()->post('id');
         }
         if (empty($id) || !($this->model = $this->model->findOne($id))) {
             return $returnJson ? $this->renderJson() : false;
         }
     }
     if (in_array($operation, ['edit', 'add'])) {
         $this->model->setAttributes(\Yii::$app->getRequest()->post());
         $result = $this->model->save();
         return $returnJson ? $this->renderJson() : $result;
     }
     if ($operation == 'del') {
         $ids = \Yii::$app->getRequest()->post('id');
         if ($ids) {
             $ids = explode(',', $ids);
             if ($this->model->deleteAll([$primaryKey => $ids])) {
                 return Json::encode(['success' => 1, 'message' => \Yii::t('yincart', 'Delete Success!')]);
             }
         }
         return Json::encode(['success' => 0, 'message' => \Yii::t('yincart', 'Error ID!'), 'errors' => []]);
     }
     return false;
 }
Esempio n. 13
0
    public function registerJs($inputId, $dropzoneId)
    {
        $settings = $this->defaults;
        $request = Yii::$app->request;
        if ($request->enableCsrfValidation) {
            $settings['params'] = [$request->csrfParam => $request->getCsrfToken()];
        }
        $successCallback = <<<JS
        function (file, data){
            if (data.uploadId) {
                file.uploadId = data.uploadId;
                \$('#{$inputId}').val(data.uploadId);
            }
        }
JS;
        $settings['success'] = new JsExpression($successCallback);
        $removeCallback = <<<JS
        function (file){
            if(confirm('Are you sure want to remove file?')){
                if(file.uploadId){
                    \$.post('{$settings['removeUrl']}', {
                        uploadId:file.uploadId
                    }).success(function(data){
                        if(\$('#{$inputId}').val() == data.id){
                           \$('#{$inputId}').val('');
                        }
                    })
                }
                if (file.previewElement && file.previewElement.parentNode) {
                    file.previewElement.parentNode.removeChild(file.previewElement);
                }
                return this._updateMaxFilesReachedClass();
            } else {
                return false;
            }


        }
JS;
        $settings['removedfile'] = new JsExpression($removeCallback);
        $existingFiles = [];
        if ($this->existingFile) {
            $existingFiles = [$this->existingFile->uploadInfo];
        }
        $encodedExistingFiles = Json::encode($existingFiles);
        $encodedConfig = Json::encode($settings);
        $init = <<<JS
        Dropzone.autoDiscover = false;
        var dz = new Dropzone("#{$dropzoneId}", {$encodedConfig});
        var files = {$encodedExistingFiles};
        files.forEach(function(file){
            dz.emit("addedfile", file);
            dz.emit("thumbnail", file, file.url);
            dz.emit("complete", file);
        })
        dz.options.maxFiles = dz.options.maxFiles - files.length;
JS;
        DropzoneAsset::register(Yii::$app->view);
        Yii::$app->view->registerJS($init);
    }
Esempio n. 14
0
    /**
     * @inheritdoc
     */
    public function run()
    {
        echo Html::tag('div', null, ['id' => $this->containerId, 'style' => 'display:none']);
        $view = $this->getView();
        PushStreamAsset::register($view);
        $options = Json::encode($this->pluginOptions);
        $channels = '';
        foreach ((array) $this->channels as $channel) {
            $channels .= $this->pusher . ".addChannel('{$channel}');";
        }
        $js = <<<JS
            var {$this->pusher} = new PushStream({$options});
            {$channels}
            {$this->pusher}.onmessage = function (text, id, channel) {
                \$.each(text.events, function (index, event) {
                    \$('#{$this->containerId}').trigger({
                        channel: channel,
                        type: event.name,
                        body: event.body
                    });
                });
            };
JS;
        if ($this->connect) {
            $js .= $this->pusher . '.connect();';
        }
        $view->registerJs($js);
    }
 public function actionSubcat()
 {
     $out = [];
     $isEmpty = true;
     if (isset($_POST['depdrop_parents'])) {
         $parents = $_POST['depdrop_parents'];
         if ($parents != null) {
             $cat_id = $parents[0];
             $out = Group::getDropDownList($cat_id);
             //$out = [['id'=>'1', 'name'=>$cat_id],['id'=>'2', 'name'=>json_encode(Group::getDropDownList($cat_id))]];
             $isEmpty = false;
             $selected = '';
             if (!empty($_POST['depdrop_params'])) {
                 $params = $_POST['depdrop_params'];
                 $selected = $params[0];
                 // get the value of input-type-1
                 $param2 = $params[1];
                 // get the value of input-type-2
             }
             echo Json::encode(['output' => $out, 'selected' => $selected]);
         }
     }
     if ($isEmpty) {
         echo Json::encode(['output' => [['id' => '1', 'name' => '<sub-cat-name1>'], ['id' => '2', 'name' => '<sub-cat-name2>']], 'selected' => '']);
     }
 }
Esempio n. 16
0
 protected function registerAssets()
 {
     CYiiAsset::register($this->view)->registerScripts();
     $options = Json::encode($this->options);
     $js = "var {$this->id} = c3.generate({$options});";
     $this->view->registerJs($js, View::POS_READY, uniqid(__CLASS__ . '#' . $this->id));
 }
Esempio n. 17
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     FlagIconAsset::register($this->getView());
     $locales = [];
     $ids = [];
     $countryRepository = new Country();
     $data = $countryRepository->findAll();
     foreach ($this->currencies as $value) {
         $key = $value->id;
         if (!empty($value->country_flag)) {
             $locales[$key] = FlagIcon::flag($value->country_flag);
         } else {
             // iterate data (countries list) to find country code with defined ($value->code) currency
             foreach ($data as $code => $country_value) {
                 if (strcasecmp($country_value->currency['code'], $value->code) == 0) {
                     $locales[$key] = FlagIcon::flag($code);
                     break;
                 }
             }
         }
         $ids[$key] = $value->code;
     }
     $currencyFormat = 'function currencyFormat(state) {
         var locales = ' . Json::encode($locales) . ';
         if (!state.id) { return state.text; }
         return locales[state.id] + " " + state.text;
     }';
     $escape = new JsExpression('function(m) { return m; }');
     $this->getView()->registerJs($currencyFormat, View::POS_HEAD);
     $this->options = array_merge(['placeholder' => Yii::$app->translate->t('select currency')], $this->options);
     $pluginOptions = array_merge(['templateResult' => new JsExpression('currencyFormat'), 'templateSelection' => new JsExpression('currencyFormat'), 'escapeMarkup' => $escape], $this->pluginOptions);
     $pluginEvents = array_merge([], $this->pluginEvents);
     return Select2::widget(['model' => $this->model, 'attribute' => $this->attribute, 'name' => $this->name, 'value' => $this->value, 'options' => $this->options, 'data' => $ids, 'pluginOptions' => $pluginOptions, 'pluginEvents' => $pluginEvents]);
 }
Esempio n. 18
0
 public function actionAddComment()
 {
     if (\Yii::$app->request->isAjax) {
         $model = new Comment();
         if (\Yii::$app->user->isGuest) {
             $model->scenario = 'isGuest';
         }
         $data = ['error' => true];
         if ($model->load(\Yii::$app->request->post())) {
             $parentID = \Yii::$app->request->post('parent_id');
             $root = $model->makeRootIfNotExist();
             if (!$parentID) {
                 $model->appendTo($root);
             } else {
                 $parent = Comment::find()->where(['id' => $parentID])->one();
                 $model->appendTo($parent);
             }
             $articleModel = Article::findOne($model->model_id);
             $data = ['replaces' => [['what' => '#comments', 'data' => $this->renderAjax('@app/themes/basic/modules/article/views/default/_comments', ['model' => $articleModel])]]];
         }
         return Json::encode($data);
     } else {
         throw new NotFoundHttpException(\Yii::t('app', 'Page not found'));
     }
 }
Esempio n. 19
0
 /**
  * @param View $view
  * @return static the registered asset bundle instance
  */
 public static function register($view)
 {
     $configOptions = [];
     $configSelector = self::DEFAULT_SELECTOR;
     try {
         $thisBundle = \Yii::$app->getAssetManager()->getBundle(__CLASS__);
         $configOptions = $thisBundle->options;
         $configSelector = $thisBundle->selector;
     } catch (\Exception $e) {
         // do nothing...
     }
     $options = empty($configOptions) ? '' : Json::encode($configOptions);
     if ($configSelector !== self::DEFAULT_SELECTOR) {
         $view->registerJs('
             hljs.configure(' . $options . ');
             jQuery(\'' . $configSelector . '\').each(function(i, block) {
                 hljs.highlightBlock(block);
             });');
     } else {
         $view->registerJs('
             hljs.configure(' . $options . ');
             hljs.initHighlightingOnLoad();', View::POS_END);
     }
     return parent::register($view);
 }
Esempio n. 20
0
 public function actionLike($id)
 {
     if (Yii::$app->user->isGuest) {
         $r = [];
         $r['e'] = Yii::t('app', 'Нужно войти на сайт под своим логином или зарегистрироваться');
         echo Json::encode($r);
         Yii::$app->end();
     }
     $model = HashtagDescription::find()->where("id = :id", [':id' => $id])->one();
     if (!$model) {
         throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
     }
     $like = HashtagDescriptionLike::find()->where("description = :description AND user = :user", [':description' => $model->id, ':user' => Yii::$app->user->id])->one();
     if ($like) {
         $r = [];
         $r['e'] = Yii::t('app', 'Ваш голос уже учтен!');
         echo Json::encode($r);
         Yii::$app->end();
     }
     $model->likes = $model->likes + 1;
     $model->save();
     $like = new HashtagDescriptionLike();
     $like->description = $model->id;
     $like->user = Yii::$app->user->id;
     if ($like->validate()) {
         $like->save();
     }
     $r = [];
     $r['likes'] = (int) $model->likes;
     echo Json::encode($r);
 }
 public function init()
 {
     if ($this->_module == null) {
         $this->_module = Yii::$app->getModule('cackle_reviews');
     }
     if (!$this->_module) {
         throw new InvalidConfigException("Не определен модуль в конфигурации проекта");
     }
     /*Устанавливаем по умолчанию канал равный адресу страницы*/
     if (!$this->params['channel']) {
         $this->params['channel'] = Yii::$app->request->url;
     }
     /*Синхронизация комментариев*/
     if ($this->sync) {
         $sync = new helpers\CackleReviewSync();
         $sync->sync();
     }
     $this->_uid = uniqid(time());
     $this->params['widget'] = 'Review';
     $this->params['id'] = $this->_module->site_id;
     $this->params['chanWithoutParams'] = true;
     $this->params['container'] = 'mc-review-' . $this->_uid;
     $js = 'cackle_widget.push(' . Json::encode($this->params) . ');';
     $cackle_pos_end = 'document.getElementById("mc-review-' . $this->_uid . '").innerHTML = "";';
     $cackle_pos_end .= 'cackle_widget = window.cackle_widget || [];';
     $cackle_pos_end .= "\r\n        (function() {\r\n            var mc = document.createElement('script');\r\n            mc.type = 'text/javascript';\r\n            mc.async = true;\r\n            mc.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://cackle.me/widget.js';\r\n            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);\r\n        })();";
     $this->getView()->registerJs($js, View::POS_READY, 'cackle_init_' . $this->_uid);
     $this->getView()->registerJs($cackle_pos_end, View::POS_END, 'cackle_load');
     parent::init();
 }
Esempio n. 22
0
 public function run()
 {
     Assets::register($this->getView());
     echo Html::beginTag('div', $this->containerOptions);
     if ($this->hasModel()) {
         echo Html::activeTextarea($this->model, $this->attribute, $this->options);
     } else {
         echo Html::textarea($this->name, $this->value, $this->options);
     }
     echo Html::endTag('div');
     $js = ['mihaildev.ckEditor.registerOnChange(' . Json::encode($this->options['id']) . ');'];
     if (isset($this->editorOptions['filebrowserUploadUrl'])) {
         $js[] = "mihaildev.ckEditor.registerCsrf();";
     }
     if (!isset($this->editorOptions['on']['instanceReady'])) {
         $this->editorOptions['on']['instanceReady'] = new JsExpression("function( ev ){" . implode(' ', $js) . "}");
     }
     if ($this->_inline) {
         $JavaScript = "CKEDITOR.inline(";
         $JavaScript .= Json::encode($this->options['id']);
         $JavaScript .= empty($this->editorOptions) ? '' : ', ' . Json::encode($this->editorOptions);
         $JavaScript .= ");";
         $JavaScript .= "\$('#" . $this->options['id'] . "').on('change', function() {\n                function periodicData(data) {\n                    \$.ajax({\n                        type: 'POST',\n                        url: '" . $this->dataUrlEdit . "',\n                        dataType: 'json',\n                        data: {data: data,'attr':'" . $this->name . "'},\n                        beforeSend: function (data) {},\n                        success: function (data) {console.log(data)},\n                        error: function (xhr, ajaxOptions, thrownError) {\n                            alert(xhr.status);\n                            alert(thrownError);\n                        },\n                        complete: function (data) {}\n                    });\n                }\n                periodicData(\$(this).val());\n            });";
         $this->getView()->registerJs($JavaScript, View::POS_END);
         $this->getView()->registerCss('#' . $this->containerOptions['id'] . ', #' . $this->containerOptions['id'] . ' .cke_textarea_inline{height: ' . $this->editorOptions['height'] . 'px;}');
     } else {
         $JavaScript = "CKEDITOR.replace(";
         $JavaScript .= Json::encode($this->options['id']);
         $JavaScript .= empty($this->editorOptions) ? '' : ', ' . Json::encode($this->editorOptions);
         $JavaScript .= ");";
         $this->getView()->registerJs($JavaScript, View::POS_END);
     }
 }
    protected function editable()
    {
        $id = $this->id;
        $autocompletion = $this->autocompletion ? 'true' : 'false';
        if ($this->autocompletion) {
            $this->aceOptions['enableBasicAutocompletion'] = true;
            $this->aceOptions['enableSnippets'] = true;
            $this->aceOptions['enableLiveAutocompletion'] = false;
        }
        $aceOptions = Json::encode($this->aceOptions);
        $js = <<<JS
(function(){
    var aceEditorAutocompletion = {$autocompletion};

    if (aceEditorAutocompletion) {
        ace.require("ace/ext/language_tools");
    }

    {$this->varNameAceEditor} = ace.edit("{$id}");
    {$this->varNameAceEditor}.setTheme("ace/theme/{$this->theme}");
    {$this->varNameAceEditor}.getSession().setMode("ace/mode/{$this->mode}");
    {$this->varNameAceEditor}.setOptions({$aceOptions});
})();
JS;
        $view = $this->getView();
        $view->registerJs("\nvar {$this->varNameAceEditor} = {};\n", $view::POS_HEAD);
        $view->registerJs($js);
        if ($this->hasModel()) {
            return Html::activeTextarea($this->model, $this->attribute, $this->options);
        }
        return Html::textarea($this->name, $this->value, $this->options);
    }
Esempio n. 24
0
 public function getConfig()
 {
     if (!isset($this->configuration) || !is_array($this->configuration) || empty($this->configuration)) {
         throw new InvalidConfigException("You should define 'configuration' option and add values according to the documentation!");
     }
     return \yii\helpers\Json::encode($this->configuration);
 }
Esempio n. 25
0
 public function ajaxReturn($status, $data, $note)
 {
     $response = Yii::$app->getResponse();
     $response->content = Json::encode(['status' => (int) $status, 'data' => $data, 'note' => $note]);
     $response->send();
     die;
 }
Esempio n. 26
0
 public function actionGetCityProvince($zipId)
 {
     // find the zip code from the locations table
     $location = Locations::findOne($zipId);
     echo Json::encode($location);
     exit;
 }
 /**
  * Constructor.
  * @param integer $status HTTP status code, such as 404, 500, etc.
  * @param string $message error message
  * @param \Exception $previous The previous exception used for the exception chaining.
  */
 public function __construct($message = null)
 {
     if (is_array($message)) {
         $message = Json::encode($message);
     }
     parent::__construct(503, $message, null);
 }
Esempio n. 28
0
 /**
  * @param $documentClass \gromver\platform\common\models\elasticsearch\ActiveDocument
  * @return int
  * @throws \yii\elasticsearch\Exception
  */
 public function upload($documentClass)
 {
     $bulk = '';
     /** @var \yii\db\ActiveRecord|string $modelClass */
     $modelClass = $documentClass::model();
     /** @var \gromver\platform\common\models\elasticsearch\ActiveDocument $document */
     $document = new $documentClass();
     $uploaded = 0;
     foreach ($modelClass::find()->each() as $model) {
         /** @var \yii\db\ActiveRecord $model */
         $action = Json::encode(["index" => ["_id" => $model->getPrimaryKey(), "_type" => $documentClass::type(), "_index" => $documentClass::index()]]);
         $document->loadModel($model);
         $data = Json::encode($document->toArray());
         $bulk .= $action . "\n" . $data . "\n";
         $uploaded++;
     }
     $url = [$documentClass::index(), $documentClass::type(), '_bulk'];
     $response = ActiveRecord::getDb()->post($url, [], $bulk);
     $n = 0;
     $errors = [];
     foreach ($response['items'] as $item) {
         if (isset($item['index']['status']) && ($item['index']['status'] == 201 || $item['index']['status'] == 200)) {
             $n++;
         } else {
             $errors[] = $item['index'];
         }
     }
     if (!empty($errors) || isset($response['errors']) && $response['errors']) {
         throw new Exception(__METHOD__ . ' failed inserting ' . $modelClass . ' model records.', $errors);
     }
     return $n;
 }
Esempio n. 29
-1
 /**
  * Generates a hashed variable to store the plugin `clientOptions`. Helps in reusing the variable for similar
  * options passed for other widgets on the same page. The following special data attribute will also be
  * setup for the input widget, that can be accessed through javascript:
  *
  * - 'data-plugin-tagsinput' will store the hashed variable storing the plugin options.
  *
  * @param View $view the view instance
  */
 protected function hashPluginOptions($view)
 {
     $encOptions = empty($this->clientOptions) ? '{}' : Json::encode($this->clientOptions);
     $this->_hashVar = self::PLUGIN_NAME . '_' . hash('crc32', $encOptions);
     $this->options['data-plugin-' . self::PLUGIN_NAME] = $this->_hashVar;
     $view->registerJs("var {$this->_hashVar} = {$encOptions};\n", View::POS_HEAD);
 }
Esempio n. 30
-1
    public function registerJs()
    {
        AssetsCallBack::register($this->getView());
        $js = "mihaildev.elFinder.register(" . Json::encode($this->options['id']) . ", function(file, id){\n                \$('#' + id).val(file.url); return true;\n            });\n            \$('#" . $this->buttonOptions['id'] . "').click(function(){\n                mihaildev.elFinder.openManager(" . Json::encode($this->_managerOptions) . ");});";
        $this->getView()->registerJs($js);
        $this->getView()->registerJs("mihaildev.elFinder.register(" . Json::encode($this->options['id']) . ", function(file, id){\n                var img;\n                if((\"url\" in file )){\n                    img = templateItem.replace('{src}', file.url).replace('{src}', file.url);\n                    \$('#{$this->previewId}').append(img);\n                } else {\n                    file.forEach(function(item){\n                        img = templateItem.replace('{src}', item.url).replace('{src}', item.url);\n                        \$('#{$this->previewId}').append(img);\n                    });\n                }\n                return true;}); ");
        $hiddenInput = Html::activeHiddenInput($this->model, $this->attribute . '[]', ['value' => '{src}']);
        $templateJS = 'var templateItem = \'<div class="image-preview-wrap">
  <div class="image-preview">
    <img src="{src}" alt="">
  </div>
  <div class="delete-button">
    <a class="delete-image">
      <span class="glyphicon glyphicon-remove"></span>
    </a>
  </div>
  ' . $hiddenInput . '
</div>\';';
        $this->getView()->registerJs(str_replace(["\r", "\n"], '', $templateJS), \yii\web\View::POS_END);
        $deleteJs = '$(document).on("click", ".delete-button", function(){$(this).parent().remove()});';
        $this->getView()->registerJs($deleteJs);
        $this->view->registerCss('.form-img-preview {max-width:100px;}');
        $this->view->registerCss('.image-preview img {max-width:200px;}');
        $this->view->registerCss('.image-preview-wrap {position: relative;display: inline-block;max-width: 200px;margin: 10px;}');
        $this->view->registerCss('.delete-button {top: 0;position: absolute;right: 0;}');
    }