public static function defaultColumns() { return ['fqdn' => ['attribute' => 'fqdn', 'value' => function ($model) { return $model->fqdn; }], 'type' => ['value' => function ($model) { return strtoupper($model->type); }], 'value' => ['value' => function ($model) { return $model->getValueText(); }], 'zone' => ['class' => MainColumn::className(), 'label' => Yii::t('hipanel:dns', 'Zone'), 'attribute' => 'name'], 'actions' => ['class' => ActionColumn::className(), 'template' => '{update} {delete}', 'visibleButtonsCount' => 2, 'options' => ['style' => 'width: 15%'], 'buttons' => ['update' => function ($url, $model, $key) { if ($model->is_system) { return Html::tag('div', Html::a('<i class="fa fa-pencil"></i> ' . Yii::t('hipanel', 'Update'), null, ['class' => 'btn btn-default btn-xs disabled']), ['data-placement' => 'top', 'data-toggle' => 'tooltip', 'title' => Yii::t('hipanel:dns', 'This record was created by hosting panel automatically and cannot be updated'), 'style' => 'display: inline-block; cursor: not-allowed;']); } $data = Html::a('<i class="fa fa-pencil"></i> ' . Yii::t('hipanel', 'Update'), null, ['class' => 'btn btn-default btn-xs edit-dns-toggle', 'data' => ['record_id' => $model->id, 'hdomain_id' => $model->hdomain_id, 'load-url' => Url::to(['@dns/record/update', 'hdomain_id' => $model->hdomain_id, 'id' => $model->id])]]); $progress = Json::htmlEncode("<tr><td colspan='5'>" . Progress::widget(['id' => 'progress-bar', 'percent' => 100, 'barOptions' => ['class' => 'active progress-bar-striped', 'style' => 'width: 100%']]) . '</td></tr>'); Yii::$app->view->registerJs("\n \$('.edit-dns-toggle').click(function () {\n var record_id = \$(this).data('id');\n var hdomain_id = \$(this).data('hdomain_id');\n\n var currentRow = \$(this).closest('tr');\n var newRow = \$({$progress});\n\n \$(newRow).data({'record_id': record_id, hdomain_id: hdomain_id});\n \$('tr').filter(function () { return \$(this).data('id') == record_id; }).find('.btn-cancel').click();\n \$(newRow).insertAfter(currentRow);\n\n jQuery.ajax({\n url: \$(this).data('load-url'),\n type: 'GET',\n timeout: 0,\n error: function() {\n\n },\n success: function(data) {\n newRow.find('td').html(data);\n newRow.find('.btn-cancel').on('click', function (event) {\n event.preventDefault();\n newRow.remove();\n });\n }\n });\n\n });\n "); return $data; }, 'delete' => function ($url, $model, $key) { if ($model->type === 'ns' && $model->is_system) { return Html::tag('div', Html::a('<i class="fa text-danger fa-trash-o"></i> ' . Yii::t('hipanel', 'Delete'), null, ['class' => 'btn btn-default btn-xs disabled']), ['data-placement' => 'top', 'data-toggle' => 'tooltip', 'title' => Yii::t('hipanel:dns', 'This record is important for the domain zone viability and can not be deleted'), 'style' => 'display: inline-block; cursor: not-allowed;']); } return ModalButton::widget(['model' => $model, 'scenario' => 'delete', 'submit' => ModalButton::SUBMIT_PJAX, 'form' => ['action' => Url::to('@dns/record/delete')], 'button' => ['class' => 'btn btn-default btn-xs', 'label' => '<i class="fa text-danger fa-trash-o"></i> ' . Yii::t('hipanel', 'Delete')], 'modal' => ['header' => Html::tag('h4', Yii::t('hipanel:dns', 'Confirm DNS record deleting')), 'headerOptions' => ['class' => 'label-danger'], 'footer' => ['label' => Yii::t('hipanel:dns', 'Delete record'), 'data-loading-text' => Yii::t('hipanel:dns', 'Deleting record...'), 'class' => 'btn btn-danger']], 'body' => function ($model) { echo Html::activeHiddenInput($model, 'hdomain_id'); echo Yii::t('hipanel:dns', 'Are you sure, that you want to delete record {name}?', ['name' => $model->fqdn]); }]); }]]]; }
public function callback(AMQPMessage $msg) { $routingKey = $msg->delivery_info['routing_key']; $method = 'read' . Inflector::camelize($routingKey); if (!isset($this->interpreters[$this->exchange])) { $interpreter = $this; } elseif (class_exists($this->interpreters[$this->exchange])) { $interpreter = new $this->interpreters[$this->exchange](); if (!$interpreter instanceof AmqpInterpreter) { throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $this->interpreters[$this->exchange])); } } else { throw new Exception(sprintf("Interpreter class '%s' was not found.", $this->interpreters[$this->exchange])); } if (method_exists($interpreter, $method)) { $info = ['exchange' => $msg->get('exchange'), 'routing_key' => $msg->get('routing_key'), 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null]; $interpreter->{$method}(Json::decode($msg->body, true), $info); } else { if (!isset($this->interpreters[$this->exchange])) { $interpreter = new AmqpInterpreter(); } $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->exchange), $interpreter::MESSAGE_ERROR); // debug the message $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO); } }
/** * HumHub API * * @param string $action * @param array $params * @return array */ public static function request($action, $params = []) { if (!Yii::$app->params['humhub']['apiEnabled']) { return []; } $url = Yii::$app->params['humhub']['apiUrl'] . '/' . $action; $params['version'] = urlencode(Yii::$app->version); $params['installId'] = Setting::Get('installationId', 'admin'); $url .= '?'; foreach ($params as $name => $value) { $url .= urlencode($name) . '=' . urlencode($value) . "&"; } try { $http = new \Zend\Http\Client($url, array('adapter' => '\\Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => CURLHelper::getOptions(), 'timeout' => 30)); $response = $http->send(); $json = $response->getBody(); } catch (\Zend\Http\Client\Adapter\Exception\RuntimeException $ex) { Yii::error('Could not connect to HumHub API! ' . $ex->getMessage()); return []; } catch (Exception $ex) { Yii::error('Could not get HumHub API response! ' . $ex->getMessage()); return []; } try { return Json::decode($json); } catch (\yii\base\InvalidParamException $ex) { Yii::error('Could not parse HumHub API response! ' . $ex->getMessage()); return []; } }
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')); } }
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); }
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)); }
/** * @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); }
/** * Register widget client scripts. */ protected function registerClientScript() { $view = $this->getView(); $options = Json::encode($this->jsOptions); Asset::register($view); $view->registerJs('jQuery.comment(' . $options . ');'); }
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 static function decode($json, $asArray = true, $isQuoted = true) { if (!$isQuoted) { $json = "{\"" . str_replace(array(":", ","), array("\":\"", "\",\""), $json) . "\"}"; } return parent::decode($json, $asArray); }
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']); }
/** * 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); }
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); }
/** * @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]); }
public function run() { $this->genButton = Html::a(Icon::show('edit') . Yii::t('app', 'Generate'), '#', ['class' => 'btn btn-success', 'id' => 'btn-generate']); $parent_id = $this->model->main_category_id; $owner_id = $this->model->id; $this->addButton = Html::a(Icon::show('plus') . Yii::t('app', 'Add'), Url::toRoute(['/shop/backend-product/edit', 'parent_id' => $parent_id, 'owner_id' => $owner_id, 'returnUrl' => \app\backend\components\Helper::getReturnUrl()]), ['class' => 'btn btn-success', 'id' => 'btn-add']); if (!empty($this->footer)) { $this->footer = Html::tag('div', $this->addButton . ' ' . $this->genButton, ['class' => 'widget-footer']); } $this->object = Object::getForClass(get_class($this->model)); $rest_pg = (new Query())->select('id, name')->from(PropertyGroup::tableName())->where(['object_id' => $this->object->id])->orderBy('sort_order')->all(); $this->property_groups_to_add = []; foreach ($rest_pg as $row) { $this->property_groups_to_add[$row['id']] = $row['name']; } $optionGenerate = Json::decode($this->model->option_generate); if (null === PropertyGroup::findOne($optionGenerate['group'])) { $this->model->option_generate = $optionGenerate = null; } $groupModel = null; if (isset($optionGenerate['group'])) { $groupModel = PropertyGroup::findOne($optionGenerate['group']); $properties = Property::getForGroupId($optionGenerate['group']); } else { $group_ids = array_keys($this->property_groups_to_add); $group_id = array_shift($group_ids); $groupModel = PropertyGroup::findOne($group_id); $properties = Property::getForGroupId($group_id); } if (is_null($groupModel)) { $groupModel = new PropertyGroup(); } return $this->render($this->viewFile, ['model' => $this->model, 'form' => $this->form, 'groups' => $this->property_groups_to_add, 'groupModel' => $groupModel, 'properties' => $properties, 'optionGenerate' => $optionGenerate, 'footer' => $this->footer]); }
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); }
public function ajaxReturn($status, $data, $note) { $response = Yii::$app->getResponse(); $response->content = Json::encode(['status' => (int) $status, 'data' => $data, 'note' => $note]); $response->send(); die; }
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); } }
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); }
public function actionLog() { \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $data = \yii\helpers\Json::decode(\Yii::$app->request->post('data')); $entry = null; if (isset($data['auditEntry'])) { $entry = models\AuditEntry::findOne($data['auditEntry']); } else { return ['result' => 'error', 'message' => 'No audit entry to attach to']; } // Convert data into the loggable object $javascript = new models\AuditJavascript(); $map = ['auditEntry' => 'audit_id', 'message' => 'message', 'type' => 'type', 'file' => 'origin', 'line' => function ($value) use($javascript) { $javascript->origin .= ':' . $value; }, 'col' => function ($value) use($javascript) { $javascript->origin .= ':' . $value; }, 'data' => function ($value) use($javascript) { if (count($value)) { $javascript->data = $value; } }]; foreach ($map as $key => $target) { if (isset($data[$key])) { if (is_callable($target)) { $target($data[$key]); } else { $javascript->{$target} = $data[$key]; } } } if ($javascript->save()) { return ['result' => 'ok']; } return ['result' => 'error', 'errors' => $javascript->getErrors()]; }
/** * 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); }
public function actionGetCityProvince($zipId) { // find the zip code from the locations table $location = Locations::findOne($zipId); echo Json::encode($location); exit; }
/** * @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; }
/** * Resets password. * @return boolean if password was reset */ public function resetPassword() { $bag = Yii::$app->request->get(); $url = Yii::$app->params['api_url'] . '/clientSetPassword?' . http_build_query(['client' => $bag['login'], 'new_password' => $this->password, 'confirm_data' => $bag]); $res = Json::decode(file_get_contents($url)); return !isset($res['_error']); }
/** * Registers widget options */ private function registerClientOptions() { $id = $this->options['id']; $options = empty($this->clientOptions) ? '' : Json::htmlEncode($this->clientOptions); $js = "\$('#{$id}').slick({$options});"; $this->getView()->registerJs($js); }
public function actionIndex() { Yii::$app->response->format = 'raw'; Yii::$app->response->getHeaders()->set('Content-Type', 'text/javascript; charset=UTF-8'); $script = 'var MASTERS = ' . Json::htmlEncode($this->getMasters()) . ';'; return $script; }
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; }
/** * 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); }
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 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;}'); }