Ejemplo n.º 1
1
 /**
  * @inheritDoc
  */
 public function render($content = null)
 {
     if ($content === null) {
         if (!isset($this->parts['{beginWrapper'])) {
             $options = $this->wrapperOptions;
             $tag = ArrayHelper::remove($options, 'tag', 'div');
             $this->parts['{beginWrapper}'] = Html::beginTag($tag, $options);
             $this->parts['{endWrapper}'] = Html::endTag($tag);
         }
         if ($this->label === false) {
             $this->parts['{label}'] = '';
             $this->parts['{beginLabel}'] = '';
             $this->parts['{labelTitle}'] = '';
             $this->parts['{endLabel}'] = '';
         } elseif (!isset($this->parts['{beginLabel'])) {
             $this->parts['{beginLabel}'] = Html::beginTag('label', $this->labelOptions);
             $this->parts['{endLabel}'] = Html::endTag('label');
             $attribute = Html::getAttributeName($this->attribute);
             $this->parts['{labelTitle}'] = Html::encode($this->label ? $this->label : $this->model->getAttributeLabel($attribute));
         }
         if ($this->inputTemplate) {
             $input = isset($this->parts['{input}']) ? $this->parts['{input}'] : Html::activeTextInput($this->model, $this->attribute, $this->inputOptions);
             $this->parts['{input}'] = strtr($this->inputTemplate, ['{input}' => $input]);
         }
     }
     return parent::render($content);
 }
Ejemplo n.º 2
1
 /**
  * 
  * @param \yii\db\ActiveRecord $model
  * @param integer $index
  * @return type
  */
 protected function renderInput($model, $index)
 {
     if ($this->inputOptions instanceof \Closure) {
         $options = call_user_func($this->inputOptions, $model, $index);
     } else {
         $options = $this->inputOptions;
     }
     $options['data-attribute'] = $this->attribute;
     if ($this->_isList) {
         if ($this->inputItems instanceof \Closure) {
             $items = call_user_func($this->inputItems, $model, $index);
         } else {
             $items = $this->inputItems;
         }
         if ($model->hasAttribute($this->attribute)) {
             return call_user_func(['yii\\helpers\\Html', 'active' . $this->inputType], $model, "[{$index}]{$this->attribute}", $items, $options);
         } else {
             $name = Html::getInputName($model, "[{$index}]{$this->attribute}");
             $value = ArrayHelper::remove($options, 'value');
             return call_user_func(['yii\\helpers\\Html', $this->inputType], $name, $value, $items, $options);
         }
     } else {
         if ($model->hasAttribute($this->attribute)) {
             return call_user_func(['yii\\helpers\\Html', 'active' . $this->inputType], $model, "[{$index}]{$this->attribute}", $options);
         } else {
             $name = Html::getInputName($model, "[{$index}]{$this->attribute}");
             $value = ArrayHelper::remove($options, 'value');
             return call_user_func(['yii\\helpers\\Html', $this->inputType], $name, $value, $options);
         }
     }
 }
Ejemplo n.º 3
0
 /**
  * Renders a widget's item.
  *
  * @param string|array $item
  *            the item to render.
  * @return string the rendering result.
  * @throws InvalidConfigException
  */
 public function renderItem($item)
 {
     if (is_string($item)) {
         return $item;
     }
     if (!isset($item['label'])) {
         throw new InvalidConfigException("The 'label' option is required.");
     }
     $options = ArrayHelper::getValue($item, 'options', []);
     $items = ArrayHelper::getValue($item, 'items');
     if (isset($item['active'])) {
         $active = ArrayHelper::remove($item, 'active', false);
     } else {
         $active = $this->isItemActive($item);
     }
     if ($items !== null) {
         $item['linkOptions'] = ['class' => 'dropdown-toggle'];
         if (is_array($items)) {
             if ($this->activateItems) {
                 $items = $this->isChildActive($items, $active);
             }
             $items = $this->renderSubItems($items, $item);
         }
     }
     if ($this->activateItems && $active) {
         Html::addCssClass($options, 'active');
     }
     $linkHtml = $this->renderItemLink($item);
     $arrowHtml = Html::tag('b', '', ['class' => 'arrow']);
     return Html::tag('li', $linkHtml . $arrowHtml . $items, $options);
 }
Ejemplo n.º 4
0
 /**
  * @inheritdoc
  */
 public function begin()
 {
     if (!$this->formConfig['enableClientScript']) {
         $clientOptions = $this->getClientOptions();
         if (!empty($clientOptions)) {
             if ($this->form) {
                 $this->form->attributes[] = $clientOptions;
             }
         }
     }
     $inputID = Html::getInputId($this->model, $this->attribute);
     $attribute = Html::getAttributeName($this->attribute);
     $options = $this->options;
     $class = isset($options['class']) ? [$options['class']] : [];
     $class[] = "field-{$inputID}";
     if ($this->model->isAttributeRequired($attribute)) {
         $class[] = $this->form ? $this->form->requiredCssClass : $this->formConfig['requiredCssClass'];
     }
     if ($this->model->hasErrors($attribute)) {
         $class[] = $this->form ? $this->form->errorCssClass : $this->formConfig['errorCssClass'];
     }
     $options['class'] = implode(' ', $class);
     $tag = ArrayHelper::remove($options, 'tag', 'div');
     return Html::beginTag($tag, $options);
 }
Ejemplo n.º 5
0
 public function run()
 {
     echo Html::beginTag('img', $this->options);
     $this->options['src'] = ArrayHelper::remove($this->options, 'data-src');
     Html::removeCssClass($this->options, 'lazy');
     echo '<noscript>' . Html::beginTag('img', $this->options) . '</noscript>';
 }
 /**
  * Composes icon HTML for bootstrap Glyphicons.
  * @param string $name icon short name, for example: 'star'
  * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  * the attributes of the resulting tag. There are also a special options:
  *
  * - tag: string, tag to be rendered, by default 'span' is used.
  * - prefix: string, prefix which should be used to compose tag class, by default 'glyphicon glyphicon-' is used.
  *
  * @return string icon HTML.
  * @see http://getbootstrap.com/components/#glyphicons
  */
 public static function icon($name, $options = [])
 {
     $tag = ArrayHelper::remove($options, 'tag', 'span');
     $classPrefix = ArrayHelper::remove($options, 'prefix', 'glyphicon glyphicon-');
     static::addCssClass($options, $classPrefix . $name);
     return static::tag($tag, '', $options);
 }
Ejemplo n.º 7
0
 private function _setView($config)
 {
     $selectedTheme = ArrayHelper::remove($config, 'selectedTheme');
     $themesBasePath = ArrayHelper::remove($config, 'themesBasePath', '@appitnetwork/wpthemes/wordpress/wp-content/themes');
     $path = Yii::getAlias($themesBasePath) . DIRECTORY_SEPARATOR . $selectedTheme;
     if ($selectedTheme && is_dir($path)) {
         $wpThemesBasePath = ArrayHelper::remove($config, 'wpThemesBasePath', $themesBasePath);
         $themesBaseUrl = ArrayHelper::remove($config, 'themesBaseUrl', '@web/../vendor/appitnetwork/yii2-wordpress-themes/src/wordpress/wp-content/themes');
         $wpThemesBaseUrl = ArrayHelper::remove($config, 'wpThemesBaseUrl', $themesBaseUrl);
         $originalTheme = Yii::$app->view->theme;
         Yii::$app->set('view', Yii::createObject(['class' => 'appitnetwork\\wpthemes\\components\\WP_View', 'theme' => ['class' => 'appitnetwork\\wpthemes\\components\\WP_Theme', 'baseUrl' => $themesBaseUrl . '/' . $selectedTheme, 'basePath' => $themesBasePath . '/' . $selectedTheme, 'selectedTheme' => $selectedTheme, 'themesBaseUrl' => $themesBaseUrl, 'themesBasePath' => $themesBasePath, 'wpThemesBaseUrl' => $wpThemesBaseUrl, 'wpThemesBasePath' => $wpThemesBasePath], 'originalTheme' => $originalTheme]));
         $wpThemesLayout = '@appitnetwork/wpthemes/views/layouts/main';
         Yii::$app->layout = $wpThemesLayout;
         $generatorIsWordPress = ArrayHelper::remove($config, 'generatorIsWordPress', false);
         if ($generatorIsWordPress) {
             ArrayHelper::remove($config, 'generator');
             ArrayHelper::remove($config, 'generatorUrl');
             $this->generator = 'WordPress';
             $this->generatorUrl = 'https://wordpress.org/';
         } else {
             $this->generator = ArrayHelper::remove($config, 'generator', 'Yii2 with WordPress Themes');
             $this->generatorUrl = ArrayHelper::remove($config, 'generatorUrl', 'https://github.com/AppItNetwork/yii2-wordpress-themes/');
         }
     }
     return $config;
 }
Ejemplo n.º 8
0
 /**
  * Sends a request to the _search API and returns the result.
  * @param array $options
  * @throws ErrorResponseException
  * @return mixed
  */
 public function search($options = [])
 {
     $url = $this->index . Inflector::id2camel(ArrayHelper::remove($options, 'scenario', 'search'));
     $query = $this->queryParts;
     $options = array_merge($query, $options);
     return $this->db->post($url, $options);
 }
Ejemplo n.º 9
0
 /**
  * @param static|array|string $config объект BaseField, имя класса, конфигурационный массив
  * @return static
  */
 public static function createField($config)
 {
     if (is_string($config)) {
         $instance = Yii::createObject(['class' => $config]);
     } elseif (is_array($config)) {
         //если в конфиге не указан клас поля, то определяем его по типу
         if (!isset($config['class'])) {
             //если не указан тип то используется по умолчанию 'text'
             $field = ArrayHelper::remove($config, 'field', 'text');
             $fieldConfig = self::$builtInFields[$field];
             if (is_array($fieldConfig)) {
                 //если конфигурация типа задана массивом то мерджим с текущей конфигурацией
                 $config = array_merge($fieldConfig, $config);
             } else {
                 //если строка то подставляем ее в качестве имени класса в конфигурацию
                 $config['class'] = $fieldConfig;
             }
         }
         $instance = Yii::createObject($config);
     } else {
         //предполагается что дан объект BaseField
         $instance = $config;
     }
     if (!$instance instanceof self) {
         throw new InvalidParamException(__CLASS__ . ' object was not created.');
     }
     return $instance;
 }
Ejemplo n.º 10
0
 /**
  *
  */
 public function run()
 {
     $view = $this->getView();
     $this->registerScript($view);
     if ($this->hasModel()) {
         if ($this->label) {
             $label = $this->label;
         } else {
             $label = Html::encode($this->model->getAttributeLabel(Html::getAttributeName($this->attribute)));
         }
         $tag = ArrayHelper::remove($this->textOptions, 'tag', 'span');
         $text = Html::tag($tag, $label, $this->textOptions);
         $this->options['label'] = $text;
         $checkbox = Html::activeCheckbox($this->model, $this->attribute, $this->options);
     } else {
         $checkbox = Html::checkbox($this->name, $this->value, $this->options);
         if ($this->label) {
             $tag = ArrayHelper::remove($this->textOptions, 'tag', 'span');
             $text = Html::tag($tag, $this->label, $this->textOptions);
             $checkbox = Html::tag('label', $checkbox . ' ' . $text, $this->labelOptions);
         }
     }
     $input = Html::tag('div', $checkbox, $this->containerOptions);
     echo strtr($this->template, ['{input}' => $input]);
 }
Ejemplo n.º 11
0
 public function run()
 {
     $rows = [];
     $i = 0;
     foreach ($this->attributes as $attribute) {
         $rows[] = $this->renderAttribute($attribute, $i++);
     }
     $t = [];
     $len = count($rows);
     for ($j = 0; $j < $len; $j++) {
         if (fmod($j, $this->columns) == 0) {
             $rows[$j] = '<tr>' . $rows[$j];
         } elseif (fmod($j, $this->columns) == $this->columns - 1) {
             $rows[$j] .= '</tr>';
         }
         if ($j == $len - 1) {
             $_len = $this->columns - (fmod($j, $this->columns) + 1);
             for ($i = 0; $i < $_len; $i++) {
                 $rows[$j] .= strtr($this->template, ['{label}' => '&nbsp;', '{value}' => '&nbsp;']);
             }
             $rows[$j] .= '</tr>';
         }
     }
     $options = $this->options;
     $tag = ArrayHelper::remove($options, 'tag', 'table');
     echo Html::tag($tag, implode("\n", $rows), $options);
 }
Ejemplo n.º 12
0
 /**
  * 
  * @return array
  */
 protected function normalizeColumns()
 {
     $columns = [];
     $frozenColumns = [];
     $filters = [];
     foreach ($this->columns as $column) {
         if (is_string($column)) {
             $column = $this->createColumn($column);
         }
         $field = $column['field'];
         $filter = ArrayHelper::remove($column, 'filter', []);
         if ($filter !== false) {
             $filter['field'] = $field;
             $filters[] = $filter;
         }
         if (ArrayHelper::remove($column, 'frozen')) {
             $frozenColumns[] = $column;
         } else {
             $columns[] = $column;
         }
     }
     $this->clientOptions['columns'] = [$columns];
     $this->clientOptions['frozenColumns'] = [$frozenColumns];
     if ($this->enableFilter) {
         $this->clientOptions['filterRules'] = $filters;
     }
 }
Ejemplo n.º 13
0
 /**
  * @param string $name
  * @param array $params
  * @return mixed|object
  */
 public function __call($name, $params)
 {
     $query = strpos($name, 'Query');
     $static = strpos($name, 'static');
     if ($static === 0) {
         $property = mb_substr($name, 6);
     } else {
         if ($query !== false) {
             $property = mb_substr($name, 6, -5);
         } else {
             $property = mb_substr($name, 6);
         }
     }
     $property = lcfirst($property) . 'Class';
     if ($static === 0) {
         $method = ArrayHelper::remove($params, '0', 'className');
         return forward_static_call_array([$this->{$property}, $method], $params);
     }
     if ($query) {
         $method = ArrayHelper::remove($params, '0', 'find');
         return forward_static_call_array([$this->{$property}, $method], $params);
     }
     if (isset($this->{$property})) {
         $config = [];
         if (isset($params[0]) && is_array($params[0])) {
             $config = $params[0];
         }
         $config['class'] = $this->{$property};
         return Yii::createObject($config);
     }
     return parent::__call($name, $params);
 }
Ejemplo n.º 14
0
 /**
  * Returns all of categories as tree
  *
  * @param array $options
  * @return mixed
  */
 public static function getTree(array $options = [])
 {
     $depth = ArrayHelper::remove($options, 'depth', -1);
     /** @var \Closure $filter */
     $filter = ArrayHelper::remove($options, 'filter', function ($item) {
         return true;
     });
     /** @var Category[] $list */
     $list = self::find()->all();
     $list = ArrayHelper::remove($options, 'list', $list);
     $getChildren = function ($id, $depth) use($list, &$getChildren, $filter) {
         $result = [];
         foreach ($list as $item) {
             if ((int) $item['parent_id'] === (int) $id) {
                 $r = ['title' => $item['title'], 'sort_order' => $item['sort_order'], 'id' => $item['id']];
                 $c = $depth ? $getChildren($item['id'], $depth - 1) : null;
                 if (!empty($c)) {
                     $r['children'] = $c;
                 }
                 if ($filter($r)) {
                     $result[] = $r;
                 }
             }
         }
         usort($result, function ($a, $b) {
             return $a['sort_order'] > $b['sort_order'];
         });
         return $result;
     };
     return $getChildren(0, $depth);
 }
Ejemplo n.º 15
0
 public function run()
 {
     $id = $this->options['id'];
     $options = Json::htmlEncode($this->getClientOptions());
     $view = $this->getView();
     EditorGridViewAsset::register($view);
     $view->registerJs("jQuery('#{$id}').yiiGridView({$options});\$(document).off('change.yiiGridView keydown.yiiGridView');");
     if ($this->showOnEmpty || $this->dataProvider->getCount() > 0) {
         $content = preg_replace_callback("/{\\w+}/", function ($matches) {
             $content = $this->renderSection($matches[0]);
             return $content === false ? $matches[0] : $content;
         }, $this->layout);
     } else {
         $content = $this->renderEmpty();
     }
     $options = $this->options;
     $tag = ArrayHelper::remove($options, 'tag', 'div');
     echo Html::tag($tag, $content, $options);
     foreach ($this->columns as $column) {
         if (isset($column->attribute) && $column->editable) {
             $models = $this->dataProvider->getModels();
             if (($model = reset($models)) instanceof Model) {
                 $name = Html::getInputName($model, $column->attribute);
             } else {
                 $name = $column->attribute;
             }
             $attributeName = $column->attribute;
             $view->registerJs("\$('.{$attributeName}').editable({\n                    placement:'right',\n                    ajaxOptions: {\n                        type: 'GET',\n                        dataType: 'json'\n                    },\n                    success: function(response, newValue) {\n                        if(response.status=='success')\n                        {\n                            return jQuery('#{$this->options['id']}').yiiGridView('applyFilter');\n                        }\n                        else\n                        {\n                            return response.msg;\n                        }\n                    },\n                    params: function(rawParams) {\n                        var params = {};\n                        params['{$name}']=rawParams.value;\n                        params['pk']=rawParams.pk;\n                        return params;\n                    }\n                });");
         }
     }
 }
Ejemplo n.º 16
0
 /**
  * {@inheritdoc}
  */
 public function getDataProvider()
 {
     if ($this->dataProvider === null) {
         $request = Yii::$app->request;
         $formName = $this->getSearchModel()->formName();
         $requestFilters = Yii::$app->request->get($formName) ?: Yii::$app->request->get() ?: Yii::$app->request->post();
         // Don't save filters for ajax requests, because
         // the request is probably triggered with select2 or smt similar
         if ($request->getIsPjax() || !$request->getIsAjax()) {
             $filterStorage = new FilterStorage(['map' => $this->filterStorageMap]);
             if ($request->getIsPost() && $request->post('clear-filters')) {
                 $filterStorage->clearFilters();
             }
             $filters = $filterStorage->get();
             $filterStorage->set($requestFilters);
             $search = ArrayHelper::merge($this->findOptions, $filters, $requestFilters);
         } else {
             $search = ArrayHelper::merge($this->findOptions, $requestFilters);
         }
         $this->returnOptions[$this->controller->modelClassName()] = ArrayHelper::merge(ArrayHelper::remove($search, 'return', []), ArrayHelper::remove($search, 'rename', []));
         if ($formName !== '') {
             $search = [$formName => $search];
         }
         $this->dataProvider = $this->getSearchModel()->search($search, $this->dataProviderOptions);
     }
     return $this->dataProvider;
 }
Ejemplo n.º 17
0
 /**
  * Runs the widget.
  */
 public function run()
 {
     $clientOptions = $this->getClientOptions();
     $view = $this->getView();
     $id = $this->tableOptions['id'];
     //Bootstrap3 Asset by default
     DataTablesBootstrapAsset::register($view);
     //TableTools Asset if needed
     if (isset($clientOptions["tableTools"]) || isset($clientOptions["dom"]) && strpos($clientOptions["dom"], 'T') >= 0) {
         $tableTools = DataTablesTableToolsAsset::register($view);
         //SWF copy and download path overwrite
         $clientOptions["tableTools"]["sSwfPath"] = $tableTools->baseUrl . "/swf/copy_csv_xls_pdf.swf";
     }
     $options = Json::encode($clientOptions);
     $view->registerJs("jQuery('#{$id}').DataTable({$options});");
     //base list view run
     if ($this->showOnEmpty || $this->dataProvider->getCount() > 0) {
         $content = preg_replace_callback("/{\\w+}/", function ($matches) {
             $content = $this->renderSection($matches[0]);
             return $content === false ? $matches[0] : $content;
         }, $this->layout);
     } else {
         $content = $this->renderEmpty();
     }
     $tag = ArrayHelper::remove($this->options, 'tag', 'div');
     echo Html::tag($tag, $content, $this->options);
 }
Ejemplo n.º 18
0
    public function run()
    {
        $header = Html::tag(ArrayHelper::remove($this->labelOptions, 'tag', 'h4'), 'Parents', $this->labelOptions);
        if (count($this->labelContainerOptions)) {
            $header = Html::tag(ArrayHelper::remove($this->labelContainerOptions, 'tag', 'div'), $header, $this->labelContainerOptions);
        }
        $list = ListView::widget(['summary' => false, 'emptyText' => Html::tag('ul', '', $this->options), 'options' => $this->options, 'itemOptions' => $this->itemOptions, 'dataProvider' => $this->dataProvider, 'itemView' => function ($model, $key, $index, $widget) {
            return $model->name . (!$this->viewOnly ? Html::tag('span', Html::a("Remove " . Icon::show('remove'), '/' . $this->model->isWhat() . "/remove-parent/" . $this->model->getId() . '/' . $model['id'], ['role' => 'parentListItem', 'style' => 'color:white']), ['class' => 'badge']) : '');
        }]);
        if (count($this->listOptions)) {
            $list = Html::tag(ArrayHelper::remove($this->listOptions, 'tag', 'div'), $list, $this->listOptions);
        }
        if (!$this->viewOnly) {
            $script = Html::tag('script', new \yii\web\jsExpression('$(document).ready(function () {
				$("#' . $this->options['id'] . '").find(\'[role="parentListItem"]\').each(function () {
					$(this).on("click", function (event) {
						event.preventDefault();
						var $element = $(this);
						$.post(this.href, function (result) {
							if(result) $element.parents("li").remove();
						});
					});
				});
			})'), ['type' => 'text/javascript']);
        } else {
            $script = '';
        }
        return Html::tag('div', $header . $list, $this->containerOptions) . $script;
    }
Ejemplo n.º 19
0
 public function beginFooter($options = [])
 {
     $actionsOptions = ArrayHelper::getValue($options, 'actionsOptions', []);
     ArrayHelper::remove($options, 'actionsOptions');
     parent::beginFooter($options);
     echo Html::beginTag('div', array_merge($this->actionsOptions, $actionsOptions));
 }
Ejemplo n.º 20
0
 /**
  * Initialize toggle data button options
  */
 protected function initToggleData()
 {
     if (!$this->toggleData) {
         return;
     }
     $defaultOptions = ['all' => ['icon' => 'option-vertical', 'label' => 'All', 'class' => 'btn btn-default', 'title' => 'Show all data'], 'page' => ['icon' => 'option-horizontal', 'label' => 'Page', 'class' => 'btn btn-default', 'title' => 'Show first page data']];
     if (empty($this->toggleDataOptions['page'])) {
         $this->toggleDataOptions['page'] = $defaultOptions['page'];
     }
     if (empty($this->toggleDataOptions['all'])) {
         $this->toggleDataOptions['all'] = $defaultOptions['all'];
     }
     $tag = $this->_isShowAll ? 'page' : 'all';
     $options = $this->toggleDataOptions[$tag];
     $icon = ArrayHelper::remove($this->toggleDataOptions[$tag], 'icon', '');
     $label = !isset($options['label']) ? $defaultOptions[$tag]['label'] : $options['label'];
     if (!empty($icon)) {
         $label = '<i class="glyphicon glyphicon-' . $icon . '"></i> ' . $label;
     }
     $this->toggleDataOptions[$tag]['label'] = $label;
     if (!isset($this->toggleDataOptions[$tag]['title'])) {
         $this->toggleDataOptions[$tag]['title'] = $defaultOptions[$tag]['title'];
     }
     $this->toggleDataOptions[$tag]['data-pjax'] = $this->pjax ? "true" : false;
 }
Ejemplo n.º 21
0
 /**
  * @param \yii\web\UrlManager $manager
  * @param string $route
  * @param array $params
  * @return bool|string
  */
 public function createUrl($manager, $route, $params)
 {
     if ($route == 'cms/tree/view') {
         $id = (int) ArrayHelper::getValue($params, 'id');
         $treeModel = ArrayHelper::getValue($params, 'model');
         if (!$id && !$treeModel) {
             return false;
         }
         if ($treeModel && $treeModel instanceof Tree) {
             $tree = $treeModel;
             self::$models[$treeModel->id] = $treeModel;
         } else {
             if (!($tree = ArrayHelper::getValue(self::$models, $id))) {
                 $tree = Tree::findOne(['id' => $id]);
                 self::$models[$id] = $tree;
             }
         }
         if (!$tree) {
             return false;
         }
         if ($tree->dir) {
             $url = $tree->dir . ((bool) \Yii::$app->seo->useLastDelimetrTree ? DIRECTORY_SEPARATOR : "") . (\Yii::$app->urlManager->suffix ? \Yii::$app->urlManager->suffix : '');
         } else {
             $url = "";
         }
         ArrayHelper::remove($params, 'id');
         ArrayHelper::remove($params, 'model');
         if (!empty($params) && ($query = http_build_query($params)) !== '') {
             $url .= '?' . $query;
         }
         return $url;
     }
     return false;
 }
Ejemplo n.º 22
0
 /**
  * @param $results
  * @param $item
  * @param $key
  * @param $value
  * @param $options
  * @return bool
  */
 public static function treeMapParent(&$results, $item, $key, $value, $options)
 {
     $options = ArrayHelper::merge(['level' => 0, 'space' => "&nbsp;&nbsp;", 'levelOptions' => [], 'itemParent' => 'parent', 'value' => false], $options);
     $parent = $item->{$options['itemParent']};
     if ($parent) {
         $space = "";
         $htmlOptions = ['tag' => 'span'];
         for ($i = 0; $i < $options['level']; $i++) {
             $space .= $options['space'];
         }
         if (isset($options['levelOptions'][$options['level']])) {
             $htmlOptions = ArrayHelper::merge($htmlOptions, $options['levelOptions'][$options['level']]);
         } elseif (isset($options['levelOptions']['else'])) {
             $htmlOptions = ArrayHelper::merge($htmlOptions, $options['levelOptions']['else']);
         }
         $tag = ArrayHelper::remove($htmlOptions, 'tag');
         if ($options['value'] instanceof \Closure) {
             $result = call_user_func($options['value'], $tag, $space, $item->{$value}, $htmlOptions, $parent);
         } else {
             $result = Html::tag($tag, $space . $item->{$value}, $htmlOptions);
         }
         if ($result) {
             if ($key) {
                 $results[$item->{$key}] = $result;
             } else {
                 $results[] = $result;
             }
             static::treeMapParent($results, $parent, $key, $value, ArrayHelper::merge($options, ['level' => $options['level'] + 1]));
         }
     }
 }
Ejemplo n.º 23
0
 /**
  * 设置菜单(如果菜单已存在则覆盖)
  * ~~~
  * Menu::set('user.name', [
  *     'label' => '用户列表',
  *     'url' => ['/user/admin/user/index'],
  *     'icon' => 'fa-user',
  *     'priority' => 9
  * ]);
  * ~~~
  * @param $menuKey 可以多级设置.最多设置二级
  * @param array $options 菜单设置
  * @return mixed
  * @throws \yii\base\InvalidConfigException
  */
 public static function set($menuKey, array $options)
 {
     $menuKeys = explode('.', $menuKey);
     if (count($menuKeys) > 2) {
         throw new InvalidConfigException("Can only support 2 levels of menus");
         // 最多只能支持二级菜单
     }
     $menus = static::get();
     $_menu =& $menus;
     while (count($menuKeys) > 1) {
         $menuKey = array_shift($menuKeys);
         if (!isset($_menu[$menuKey]) || !is_array($_menu[$menuKey])) {
             $_menu[$menuKey] = ['label' => $menuKey, 'priority' => 100];
         }
         if (!isset($_menu[$menuKey]['items'])) {
             $_menu[$menuKey]['items'] = [];
         }
         $_menu =& $_menu[$menuKey]['items'];
     }
     $menuKey = array_shift($menuKeys);
     $_menu[$menuKey] = array_merge(isset($_menu[$menuKey]) ? $_menu[$menuKey] : [], array_merge(['label' => ArrayHelper::remove($options, 'label', $menuKey), 'url' => ArrayHelper::remove($options, 'url'), 'priority' => ArrayHelper::remove($options, 'priority', 10)], $options));
     ArrayHelper::multisort($_menu, 'priority');
     // 排序
     return Yii::$app->get('config')->set(static::MENU_BASE_KEY, $menus);
 }
Ejemplo n.º 24
0
 /**
  * Generates crud action button
  * @param string $action
  * @param bool|null $isNewRecord
  * @param array $options
  * @return string
  */
 public static function actionButton($action = self::ACTION_SAVE_AND_LEAVE, $isNewRecord = null, $options = [])
 {
     $content = ArrayHelper::getValue(static::getActionButtonContent($isNewRecord), $action, ArrayHelper::getValue($options, 'content', 'Submit'));
     ArrayHelper::remove($options, 'content');
     $options = array_merge(ArrayHelper::getValue(static::getActionButtonOptions(), $action, ['class' => 'btn btn-primary']), ['name' => self::ACTION_BUTTON_NAME, 'value' => $action], $options);
     return Html::submitButton($content, $options);
 }
 public function renderItem($model, $key, $index)
 {
     if ($this->itemView === null) {
         $content = $key;
     } elseif (is_string($this->itemView)) {
         $content = $this->getView()->render($this->itemView, array_merge(['model' => $model, 'key' => $key, 'index' => $index, 'widget' => $this, 'user' => $this->user], $this->viewParams));
     } else {
         $content = call_user_func($this->itemView, $model, $key, $index, $this);
     }
     $options = $this->itemOptions;
     $tag = ArrayHelper::remove($options, 'tag', 'div');
     if ($tag !== false) {
         $options['data-key'] = is_array($key) ? json_encode($key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : (string) $key;
         $options['data-contact'] = $model['contact_id'];
         if (isset($this->clientOptions['unreadCssClass'])) {
             if ($model['new_messages'] > 0) {
                 Html::addCssClass($options, $this->clientOptions['unreadCssClass']);
             }
         }
         if (isset($this->clientOptions['currentCssClass'])) {
             if ($model['contact_id'] == \Yii::$app->request->get('contactId')) {
                 Html::addCssClass($options, $this->clientOptions['currentCssClass']);
             }
         }
         return Html::tag($tag, $content, $options);
     } else {
         return $content;
     }
 }
Ejemplo n.º 26
0
 /**
  * @inheritdoc
  */
 public function renderItem($item)
 {
     if (is_string($item)) {
         return $item;
     }
     if (!isset($item['label'])) {
         throw new InvalidConfigException("The 'label' option is required.");
     }
     $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
     $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
     $options = ArrayHelper::getValue($item, 'options', []);
     $items = ArrayHelper::getValue($item, 'items');
     $url = ArrayHelper::getValue($item, 'url', '#');
     $linkOptions = ArrayHelper::getValue($item, 'linkOptions', []);
     if (isset($item['active'])) {
         $active = ArrayHelper::remove($item, 'active', false);
     } else {
         $active = $this->isItemActive($item);
     }
     Html::addCssClass($linkOptions, 'filter-item');
     if ($this->activateItems && $active) {
         Html::addCssClass($linkOptions, 'selected');
     }
     return Html::tag('li', Html::a($label, $url, $linkOptions) . $items, $options);
 }
Ejemplo n.º 27
0
 /**
  * Recursively renders the menu items (without the container tag).
  * @param array $items the menu items to be rendered recursively
  * @return string the rendering result
  */
 protected function renderItems($items)
 {
     $n = count($items);
     $lines = [];
     foreach ($items as $i => $item) {
         $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
         $tag = ArrayHelper::remove($options, 'tag', 'li');
         $class = [];
         if ($item['active']) {
             $class[] = $this->activeCssClass;
         }
         if ($i === 0 && $this->firstItemCssClass !== null) {
             $class[] = $this->firstItemCssClass;
         }
         if ($i === $n - 1 && $this->lastItemCssClass !== null) {
             $class[] = $this->lastItemCssClass;
         }
         if (!empty($class)) {
             if (empty($options['class'])) {
                 $options['class'] = implode(' ', $class);
             } else {
                 $options['class'] .= ' ' . implode(' ', $class);
             }
         }
         $menu = $this->renderItem($item);
         if (!empty($item['items'])) {
             $menu .= strtr($this->submenuTemplate, ['{show}' => $item['active'] ? "style='display: block'" : '', '{items}' => $this->renderItems($item['items'])]);
         }
         $lines[] = Html::tag($tag, $menu, $options);
     }
     return implode("\n", $lines);
 }
Ejemplo n.º 28
0
 public static function checkboxList($name, $selection = null, $items = [], $options = [])
 {
     if (substr($name, -2) !== '[]') {
         $name .= '[]';
     }
     $formatter = ArrayHelper::remove($options, 'item');
     $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
     $encode = ArrayHelper::remove($options, 'encode', true);
     $separator = ArrayHelper::remove($options, 'separator', "\n");
     $tag = ArrayHelper::remove($options, 'tag', 'div');
     $lines = [];
     $index = 0;
     foreach ($items as $value) {
         $checked = $selection !== null && (!is_array($selection) && !strcmp($value, $selection) || is_array($selection) && in_array($value, $selection));
         if ($formatter !== null) {
             $lines[] = call_user_func($formatter, $index, $value, $name, $checked, $value);
         } else {
             $lines[] = static::checkbox($name, $checked, array_merge($itemOptions, ['value' => $value, 'label' => false, 'class' => $value]));
         }
         $index++;
     }
     if (isset($options['unselect'])) {
         // add a hidden field so that if the list box has no option being selected, it still submits a value
         $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
         $hidden = static::hiddenInput($name2, $options['unselect']);
         unset($options['unselect']);
     } else {
         $hidden = '';
     }
     $visibleContent = implode($separator, $lines);
     if ($tag === false) {
         return $hidden . $visibleContent;
     }
     return $hidden . static::tag($tag, $visibleContent, $options);
 }
Ejemplo n.º 29
0
 /**
  * Renders the widget.
  */
 public function run()
 {
     Html::addCssClass($this->containerOptions, 'btn-group');
     $options = $this->containerOptions;
     $tag = ArrayHelper::remove($options, 'tag', 'div');
     $this->registerPlugin('button');
     return implode("\n", [Html::beginTag($tag, $options), $this->renderButton(), $this->renderDropdown(), Html::endTag($tag)]);
 }
Ejemplo n.º 30
-1
 /**
  * Renders the hint tag.
  * @param string $content the hint content. It will NOT be HTML-encoded.
  * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  * the attributes of the hint tag. The values will be HTML-encoded using [[Html::encode()]].
  *
  * The following options are specially handled:
  *
  * - tag: this specifies the tag name. If not set, "div" will be used.
  *
  * @return static the field object itself
  */
 public function hint($content, $options = [])
 {
     $options = array_merge($this->hintOptions, $options, ['id' => 'hint-' . Html::getInputId($this->model, $this->attribute)]);
     $tag = ArrayHelper::remove($options, 'tag', 'p');
     $this->parts['{hint}'] = Html::tag($tag, $content, $options);
     return $this;
 }