public function init()
 {
     parent::init();
     $this->types = yii\helpers\ArrayHelper::merge($this->defaultTypes, $this->types);
     // pre-init string
     $this->types['string'] = Yii::createObject($this->types['string']);
 }
 /**
  * @inheritdoc
  */
 public function behaviors()
 {
     $behaviors = parent::behaviors();
     $behaviors['access']['rules'] = ArrayHelper::merge($behaviors['access']['rules'], [['allow' => true, 'actions' => ['index'], 'roles' => ['pageView']], ['allow' => true, 'actions' => ['create'], 'roles' => ['pageCreate']], ['allow' => true, 'actions' => ['update'], 'roles' => ['pageUpdate']], ['allow' => true, 'actions' => ['delete', 'batch-delete'], 'roles' => ['pageDelete']]]);
     $behaviors['verbs'] = ['class' => VerbFilter::className(), 'actions' => ['index' => ['get'], 'update' => ['get', 'put', 'post'], 'delete' => ['post', 'delete'], 'batch-delete' => ['post', 'delete']]];
     return $behaviors;
 }
Esempio n. 3
0
 public function run()
 {
     if (empty($this->name) && (!empty($this->model) && !empty($this->attribute))) {
         $this->name = Html::getInputName($this->model, $this->attribute);
     }
     if (empty($this->url)) {
         $this->url = Url::toRoute(['site/upload']);
     }
     $options = ['url' => $this->url, 'paramName' => $this->name, 'params' => []];
     if (Yii::$app->request->enableCsrfValidation) {
         $options['params'][Yii::$app->request->csrfParam] = Yii::$app->request->getCsrfToken();
     }
     if (!empty($this->message)) {
         $message = Html::tag('div', $this->message, $this->messageOptions);
     } else {
         $message = '';
     }
     $this->htmlOptions['id'] = $this->id;
     $this->options = ArrayHelper::merge($this->options, $options);
     echo Html::tag('div', $message, $this->htmlOptions);
     $this->registerAssets();
     $this->createDropzone();
     foreach ($this->eventHandlers as $event => $handler) {
         $handler = new \yii\web\JsExpression($handler);
         $this->getView()->registerJs($this->dropzoneName . ".on('{$event}', {$handler})");
     }
     $this->addFiles($this->storedFiles);
     $this->decrementMaxFiles(count($this->storedFiles));
     if ($this->sortable) {
         $options = Json::encode($this->sortableOptions);
         $this->getView()->registerJs("jQuery('#{$this->id}').sortable(" . $options . ");");
     }
 }
Esempio n. 4
0
 public function rules()
 {
     $rules = [['phone', 'trim'], ['phone', 'filter', 'filter' => function ($value) {
         return str_replace('+', '', $value);
     }], ['phone', 'string', 'min' => 11, 'max' => 12]];
     return \yii\helpers\ArrayHelper::merge(parent::rules(), $rules);
 }
Esempio n. 5
0
 public function rules()
 {
     $parentRules = parent::rules();
     $childRules = [['nickname', 'string', 'max' => '255'], ['gender', 'integer'], ['identity_num', 'string', 'length' => [15, 18]], ['qq', 'match', 'pattern' => "/^[1-9]*[1-9][0-9]*\$/i"], ['qq', 'string', 'max' => '11'], ['birthday', 'filter', 'filter' => 'strtotime', 'skipOnEmpty' => true]];
     $rules = ArrayHelper::merge($parentRules, $childRules);
     return $rules;
 }
Esempio n. 6
0
 /**
  * Registers KCFinder
  */
 protected function registerKCFinder()
 {
     $register = KCFinderAsset::register($this->view);
     $kcfinderUrl = $register->baseUrl;
     $browseOptions = ['filebrowserBrowseUrl' => $kcfinderUrl . '/browse.php?opener=ckeditor&type=files', 'filebrowserUploadUrl' => $kcfinderUrl . '/upload.php?opener=ckeditor&type=files'];
     $this->clientOptions = ArrayHelper::merge($browseOptions, $this->clientOptions);
 }
Esempio n. 7
0
 public function actionView($id)
 {
     $model = new AssignmentForm();
     $model->setScenario('auth');
     $permissions = [];
     $app = [];
     $authManager = Yii::$app->authManager;
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         foreach ($model->getAttributes() as $key => $value) {
             if (empty($value)) {
                 $model->{$key} = [];
             }
         }
         //Revokes all roles from a user.
         try {
             $authManager->revokeAll($id);
             //角色
             if (is_array($model->roles)) {
                 foreach ($model->roles as $name) {
                     $item = $authManager->getRole($name);
                     $authManager->assign($item, $id);
                 }
             }
             //权限
             $roles = ArrayHelper::merge($model->permissions, $model->app);
             if (is_array($roles)) {
                 foreach ($roles as $name) {
                     $item = $authManager->getPermission($name);
                     $authManager->assign($item, $id);
                 }
             }
         } catch (\Exception $e) {
             Yii::$app->session->setFlash('fail', $e->getMessage());
             $this->refresh();
             Yii::$app->end();
         }
         Yii::$app->session->setFlash('success', '授权成功');
         $this->redirect(['index']);
     }
     $roles = $authManager->getRoles();
     $roles = ArrayHelper::map($roles, 'name', 'name');
     foreach ($authManager->getPermissions() as $name => $role) {
         if ($role->name[0] == '/') {
             $permissions[$name] = $role->description;
         } elseif (substr($role->name, 0, 3) == 'app') {
             $app[$name] = $role->description;
         }
     }
     foreach ($authManager->getAssignments($id) as $name => $item) {
         if ($name[0] == '/') {
             $model->permissions[$authManager->getPermission($name)->description] = $name;
         } elseif (substr($name, 0, 3) == 'app') {
             $model->app[$name] = $name;
         } else {
             $model->roles[$name] = $name;
         }
     }
     $permissions = Tools::serializeRoutes($permissions);
     return $this->render('view', ['model' => $model, 'roles' => $roles, 'permissions' => $permissions, 'app' => $app]);
 }
 /**
  * @inheritdoc
  */
 public function actions()
 {
     return ArrayHelper::merge(parent::actions(), ['index' => ["gridConfig" => ['settingsData' => ['order' => SORT_ASC, 'orderBy' => "priority"]], "columns" => ['name', 'code', ['value' => function (\skeeks\cms\models\CmsContentType $model) {
         $contents = \yii\helpers\ArrayHelper::map($model->cmsContents, 'id', 'name');
         return implode(', ', $contents);
     }, 'label' => 'Контент'], 'priority']]]);
 }
 /**
  * Calculates distances and travel times between origins and destinations
  * 
  * @param array $origins Addresses or coordinates
  * @param array $destinations Addresses or coordinates
  * @param array $params
  * @return mixed|null
  */
 public function calculate(array $origins, array $destinations, $params = [])
 {
     $params['origins'] = implode('|', $origins);
     $params['destinations'] = implode('|', $destinations);
     $this->params = ArrayHelper::merge($this->params, $params);
     return parent::request();
 }
Esempio n. 10
0
 public function init()
 {
     parent::init();
     try {
         $tableSchema = Yii::$app->db->schema->getTableSchema(MenuItem::tableName());
     } catch (\yii\db\Exception $e) {
     }
     if (empty($tableSchema)) {
         return;
     }
     $models = MenuItem::find()->where(['menu_id' => $this->menu])->orderBy(['order_id' => SORT_ASC])->all();
     $items = [];
     // top menu items
     foreach ($models as $model) {
         if ($model->parent_id == 0) {
             $items[$model->id] = ['label' => $model->title, 'url' => $this->parseRoute($model->route)];
         }
     }
     foreach ($models as $model) {
         if (isset($items[$model->parent_id])) {
             $items[$model->parent_id]['items'][] = ['label' => $model->title, 'url' => $this->parseRoute($model->route)];
         }
     }
     $this->items = ArrayHelper::merge($items, $this->items);
     if (Yii::$app->user->identity && Yii::$app->user->identity->getIsAdmin()) {
         $this->items[] = ['label' => 'Admin Panel', 'url' => '/admin'];
     }
 }
Esempio n. 11
0
 public function getManagerOptions()
 {
     $options = ['url' => Url::toRoute('connect'), 'customData' => [Yii::$app->request->csrfParam => Yii::$app->request->csrfToken], 'resizable' => false];
     if (isset($_GET['CKEditor'])) {
         $options['getFileCallback'] = new JsExpression('function(file){ ' . 'window.opener.CKEDITOR.tools.callFunction(' . Json::encode($_GET['CKEditorFuncNum']) . ', file.url); ' . 'window.close(); }');
         $options['lang'] = $_GET['langCode'];
     }
     if (isset($_GET['filter'])) {
         if (is_array($_GET['filter'])) {
             $options['onlyMimes'] = $_GET['filter'];
         } else {
             $options['onlyMimes'] = [$_GET['filter']];
         }
     }
     if (isset($_GET['lang'])) {
         $options['lang'] = $_GET['lang'];
     }
     if (isset($_GET['callback'])) {
         if (isset($_GET['multiple'])) {
             $options['commandsOptions']['getfile']['multiple'] = true;
         }
         $options['getFileCallback'] = new JsExpression('function(file){ ' . 'if (window!=window.top) {var parent = window.parent;}else{var parent = window.opener;}' . 'if(parent.mihaildev.elFinder.callFunction(' . Json::encode($_GET['callback']) . ', file))' . 'window.close(); }');
     }
     if (!isset($options['lang'])) {
         $options['lang'] = ElFinder::getSupportedLanguage(Yii::$app->language);
     }
     if (!empty($this->disabledCommands)) {
         $options['commands'] = new JsExpression('ElFinderGetCommands(' . Json::encode($this->disabledCommands) . ')');
     }
     return ArrayHelper::merge($options, $this->managerOptions);
 }
Esempio n. 12
0
 /**
  * Function return array map for drop down list
  * @return array
  */
 public static function getAvailableApis()
 {
     static::getEnabledApiId();
     $all = static::find()->all();
     $map = ArrayHelper::map($all, 'id', 'name');
     return ArrayHelper::merge([0 => Yii::t('app', 'Not selected')], $map);
 }
Esempio n. 13
0
 public function init()
 {
     if (!is_array($this->formConfig)) {
         $this->formConfig = [];
     }
     if (is_array($this->formConfig)) {
         $this->formConfig = ArrayHelper::merge(static::getFormConfig(), $this->formConfig);
     }
     if (!is_array($this->inputConfig)) {
         $this->inputConfig = [];
     }
     if (is_array($this->inputConfig)) {
         $this->inputConfig = ArrayHelper::merge(static::getInputConfig(), $this->inputConfig);
     }
     if (!is_array($this->submitConfig)) {
         $this->submitConfig = [];
     }
     if (is_array($this->submitConfig)) {
         $this->submitConfig = ArrayHelper::merge(static::getSubmitConfig(), $this->submitConfig);
     }
     if (empty($this->model)) {
         $this->model = new SearchForm();
     }
     $this->registerTranslations();
 }
Esempio n. 14
0
    public function run()
    {
        $blockId = 'block_' . $this->id;
        $this->view->beginBlock($blockId);
        $inputFile = InputFile::begin(ArrayHelper::merge(['model' => $this->model, 'attribute' => $this->attribute, 'name' => $this->name, 'value' => $this->value], $this->fileInputOptions));
        $inputId = $inputFile->options['id'];
        $previewId = 'media-' . $inputId;
        InputFile::end();
        $this->view->endBlock();
        $replace['{input}'] = $this->view->blocks[$blockId];
        $replace['{img}'] = Html::tag('div', '', ['class' => 'form-media-preview', 'id' => $previewId]);
        echo strtr($this->template, $replace);
        $this->view->registerJs(<<<JS
    \$('#{$inputId}').change(function() {
        var src = \$(this).val();
        if (src != '') {
            var img = \$('<img/>').attr('src', src);
            \$('#{$previewId}').wrapInner(img);
        } else {
            \$('#{$previewId}').empty();
        }
    }).change();
JS
);
    }
Esempio n. 15
0
 public function __call($name, $arguments)
 {
     $id = md5(microtime());
     $request = ['jsonrpc' => '2.0', 'method' => $name, 'params' => $arguments, 'id' => $id];
     $jsonRequest = json_encode($request);
     $ctx = stream_context_create(\yii\helpers\ArrayHelper::merge(['http' => ['method' => 'POST', 'header' => "Content-Type: application/json-rpc\r\n", 'content' => $jsonRequest]], $this->streamContext));
     $jsonResponse = file_get_contents($this->url, false, $ctx);
     if ($jsonResponse === '') {
         throw new Exception('fopen failed', Exception::INTERNAL_ERROR);
     }
     $response = json_decode($jsonResponse);
     if ($response === null) {
         throw new Exception('JSON cannot be decoded', Exception::INTERNAL_ERROR);
     }
     if ($response->id != $id) {
         throw new Exception('Mismatched JSON-RPC IDs', Exception::INTERNAL_ERROR);
     }
     if (property_exists($response, 'error')) {
         throw new Exception($response->error->message, $response->error->code);
     } else {
         if (property_exists($response, 'result')) {
             return $response->result;
         } else {
             throw new Exception('Invalid JSON-RPC response', Exception::INTERNAL_ERROR);
         }
     }
 }
Esempio n. 16
0
 public function run()
 {
     BowerAssets::register($this->getView());
     $this->jsOption = \yii\helpers\Json::encode($this->jsOption);
     $this->getView()->registerJs("\$('#{$this->getId()}').highcharts({$this->jsOption});");
     return \yii\helpers\Html::tag('div', '', \yii\helpers\ArrayHelper::merge($this->option, ['id' => $this->getId()]));
 }
Esempio n. 17
0
 /**
  * @return string
  */
 public function run()
 {
     $modelSeacrhClass = $this->modelSearchClassName;
     if (!$modelSeacrhClass) {
         $search = new Search($this->controller->modelClassName);
         $dataProvider = $search->search(\Yii::$app->request->queryParams);
         $searchModel = $search->loadedModel;
     } else {
         $searchModel = new $modelSeacrhClass();
         $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
     }
     //Дополнительная обработка Дата провайдера
     if ($this->dataProviderCallback && is_callable($this->dataProviderCallback)) {
         $dataProviderCallback = $this->dataProviderCallback;
         $dataProviderCallback($dataProvider);
     }
     //Дополнительная обработка Дата провайдера
     if ($this->filter && is_callable($this->filter)) {
         $filter = $this->filter;
         $filter($dataProvider, \Yii::$app->request->queryParams);
     }
     $gridConfig = ['dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'adminController' => $this->controller, 'columns' => $this->columns];
     $gridConfig = ArrayHelper::merge($gridConfig, $this->gridConfig);
     $this->viewParams = ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'controller' => $this->controller, 'columns' => $this->columns, 'gridConfig' => $gridConfig];
     return parent::run();
 }
Esempio n. 18
0
 public function init()
 {
     parent::init();
     //Merge main extension config with local extension config
     $config = (include dirname(__FILE__) . '/config/main.php');
     foreach ($config as $key => $value) {
         if (is_array($value)) {
             $this->{$key} = ArrayHelper::merge($value, $this->{$key});
         } elseif (null === $this->{$key}) {
             $this->{$key} = $value;
         }
     }
     if (Yii::$app instanceof Application) {
         //Merge commands map
         Yii::$app->controllerMap = ArrayHelper::merge($this->commandMap, Yii::$app->controllerMap);
         Yii::$app->controllerMap = array_filter(Yii::$app->controllerMap);
     }
     Yii::$app->setComponents($this->components);
     //Set components
     if (count($this->components)) {
         $exists = Yii::$app->getComponents(false);
         foreach ($this->components as $component => $params) {
             if (isset($exists[$component]) && is_object($exists[$component])) {
                 unset($this->components[$component]);
             } elseif (isset($exists[$component])) {
                 $this->components[$component] = ArrayHelper::merge($params, $exists[$component]);
             }
         }
         Yii::$app->setComponents($this->components, false);
     }
     Yii::setAlias('@yiicod', realpath(dirname(__FILE__) . '/..'));
 }
Esempio n. 19
0
 public function run()
 {
     if ($this->hasModel()) {
         $replace['{input}'] = Html::activeHiddenInput($this->model, $this->attribute, $this->options);
         $attributeId = Html::getInputId($this->model, $this->attribute);
         $id = Html::getInputId($this->model, 'hydra_' . $this->attribute);
         $name = Html::getInputName($this->model, 'hydra_' . $this->attribute);
         $this->value = $this->model[$this->attribute];
     } else {
         $replace['{input}'] = Html::hiddenInput($this->name, $this->value, $this->options);
         $name = $id = 'hydra_' . $this->name;
         $attributeId = $this->name;
     }
     $fileInputName = empty($this->fileInputName) ? $name : $this->fileInputName;
     $replace['{preview}'] = 'Файл еще не загружен';
     if (!empty($this->value)) {
         $replace['{preview}'] = $this->value;
         $extension = Yii::$app->hydra->getExtension($this->value);
         if (Yii::$app->hydra->isImage($extension)) {
             $replace['{preview}'] = Html::img(Yii::$app->hydra->getCacheUrl($this->value, $this->resolution), ['id' => $id . '_image']);
         }
         $replace['{reset-button}'] = Html::tag($this->resetButton['tag'], $this->resetButton['label'], ArrayHelper::merge(['onClick' => '$("#' . $attributeId . '").val("");$("#' . $id . '_image' . '").remove();$(this).remove();'], $this->resetButton['options']));
     }
     $replace['{input}'] .= Html::fileInput($fileInputName, null, ArrayHelper::merge(['id' => $id], $this->fileInput['options']));
     return strtr($this->template, $replace);
 }
 public function run()
 {
     $this->attributeName = $this->property->name;
     $this->minAttribute = 'minValue[' . $this->property->id . ']';
     $this->maxAttribute = 'maxValue[' . $this->property->id . ']';
     $this->changeFlagAttribute = 'changeValue[' . $this->property->id . ']';
     $get = ArrayHelper::merge(Yii::$app->request->get(), Yii::$app->request->post());
     if ($this->selects) {
         $this->minValue = (int) array_values($this->selects)[0]['value'];
         $this->maxValue = (int) array_values($this->selects)[0]['value'];
         foreach ($this->selects as $select) {
             $select['value'] = (int) $select['value'];
             $this->minValue = $select['value'] < $this->minValue ? $select['value'] : $this->minValue;
             $this->maxValue = $select['value'] > $this->maxValue ? $select['value'] : $this->maxValue;
         }
         if (isset($get[$this->minAttribute]) && is_numeric($get[$this->minAttribute])) {
             $this->changeFlagDefaultValue = 1;
             $this->minValueNow = $get[$this->minAttribute];
         } else {
             $this->minValueNow = $this->minValue;
         }
         if (isset($get[$this->maxAttribute]) && is_numeric($get[$this->maxAttribute])) {
             $this->changeFlagDefaultValue = 1;
             $this->maxValueNow = $get[$this->maxAttribute];
         } else {
             $this->maxValueNow = $this->maxValue;
         }
     }
     return parent::run();
 }
Esempio n. 21
0
 public static function getItems()
 {
     $menu = [['label' => 'Главная', 'url' => ['site/index']]];
     if (Yii::$app->user->isGuest) {
         $menu[] = ['label' => 'Регистрация', 'items' => [['label' => 'Магазин', 'url' => ['registration/shop']], ['label' => 'Пользователь', 'url' => ['registration/user']]]];
     } else {
         if (Yii::$app->user->can(User::ROLE_ADMIN)) {
             $items = [['label' => 'Активные магазины', 'url' => ['user/index', 'role' => User::ROLE_SHOP]], ['label' => 'Магазины на модерации', 'url' => ['moderate-shop/index']], ['label' => 'Статусы для магазинов', 'url' => ['shop-status/index']]];
         } else {
             $items = [['label' => 'Профиль', 'url' => ['user/profile']], ['label' => 'Транзакции', 'url' => ['purchase/user-list']]];
             if (Yii::$app->user->can(User::ROLE_USER)) {
                 //                    $items = ArrayHelper::merge($items, [
                 //                        [
                 //                            'label' => 'Магазины', 'url' => ['user/shop-list']
                 //                        ],
                 //                        [
                 //                            'label' => 'Покупки', 'url' => ['purchase/user-list']
                 //                        ],
                 //                        [
                 //                            'label' => 'Покупки по рекомендации', 'url' => ['purchase/affiliate-list']
                 //                        ],
                 //                        [
                 //                            'label' => 'Порекомендовать', 'url' => ['user/recommend']
                 //                        ]
                 //                    ]);
             } elseif (Yii::$app->user->can(User::ROLE_SHOP)) {
                 $items = ArrayHelper::merge($items, [['label' => 'Ссылки', 'url' => ['url/own-list']], ['label' => 'Покупки пользователей', 'url' => ['purchase/shop-list']]]);
             }
         }
         $menu[] = ['label' => Yii::$app->user->identity->email, 'items' => $items];
     }
     $menu[] = Yii::$app->user->isGuest ? ['label' => 'Вход', 'url' => ['site/login']] : ['label' => 'Выход', 'url' => ['site/logout'], 'linkOptions' => ['data-method' => 'post']];
     return $menu;
 }
Esempio n. 22
0
 /**
  * 添加权限到角色
  */
 public function actionConfig($name)
 {
     $role = $name;
     $authManager = Yii::$app->getAuthManager();
     $roleModel = $this->findAuthItemModel($role);
     if (Yii::$app->getRequest()->post()) {
         //清空当角色的所有权限
         $authManager->removeItems($role);
         foreach (Yii::$app->getRequest()->post() as $key => $value) {
             if (!empty($value) && is_array($value)) {
                 if (in_array($key, $value)) {
                     //只存task
                     if (!$authManager->hasChild($authManager->getRole($role), $authManager->getTask($key))) {
                         $authManager->addChild($authManager->getRole($role), $authManager->getTask($key));
                     }
                 } else {
                     //只存permission
                     foreach ($value as $item) {
                         if (!$authManager->hasChild($authManager->getRole($role), $authManager->getPermission($item))) {
                             $authManager->addChild($authManager->getRole($role), $authManager->getPermission($item));
                         }
                     }
                 }
             }
         }
         //提示更新成功
         Yii::$app->getSession()->setFlash('success', Yii::t('auth', 'Update Role Success'));
     }
     $tasksAndPermissions = $authManager->getTasksAndPermissions();
     $selectItems = ArrayHelper::merge($authManager->getPermissionsByRole($role), $authManager->getTasksByRole($role));
     $selectItems = array_keys($selectItems);
     return $this->render('config', ['tasksAndPermissions' => $tasksAndPermissions, 'selectItems' => $selectItems, 'model' => $roleModel, 'name' => $role]);
 }
 /**
  * @param  DataEntityProvider[] $providers
  * @param  ActionData           $actionData
  * @param  array                $packed
  * @param  array                $providedKeys
  *
  * @return mixed
  */
 public static function process($providers, &$actionData, &$packed, &$providedKeys)
 {
     $result = [];
     $providedKeys = [];
     foreach ($providers as $i => $provider) {
         $profileKey = "DataProviderProcessor: {$i}";
         Yii::beginProfile($profileKey);
         //! @todo Add check for correct class names here
         /** @var DataEntityProvider $instance */
         $instance = Yii::createObject($provider);
         $providerResult = $instance->getEntities($actionData);
         $keys = [];
         array_walk($providerResult, function ($materials, $regionKey) use(&$keys) {
             $result = [];
             array_walk($materials, function ($data, $materialIndex) use(&$result) {
                 $result[$materialIndex] = array_keys($data);
             });
             $keys[$regionKey] = $result;
         });
         $providedKeys[$i] = $keys;
         $result = ArrayHelper::merge($result, $providerResult);
         $packed[$i] = $instance->pack();
         Yii::endProfile($profileKey);
     }
     return $result;
 }
Esempio n. 24
0
 /**
  *
  */
 public function init()
 {
     if (!$this->model instanceof ActiveRecord) {
         throw new Exception('model must be ActiveRecord and required');
     }
     $methods = ['get', 'post'];
     if (!in_array($this->method, $methods)) {
         throw new Exception('method must be get or post');
     }
     $method = $this->method;
     if (empty($this->get)) {
         $this->get = Yii::$app->request->{$method}($this->getModelName());
     }
     if (!empty($this->columns)) {
         foreach ($this->columns as $column) {
             if (is_string($column)) {
                 $column = ['attribute' => $column];
             }
             $c = new ColumnsTab(ArrayHelper::merge($column, ['model' => $this->model, 'get' => $this->get]));
             $this->tabs[] = $c->getLabel();
         }
     } else {
         foreach ($this->get as $attr => $value) {
             $c = new ColumnsTab(['model' => $this->model, 'get' => $this->get, 'attribute' => $attr]);
             $this->tabs[] = $c->getLabel();
         }
     }
     $this->tabs = array_filter($this->tabs);
 }
Esempio n. 25
0
 public function getItemConfig($id = null, array $config = [])
 {
     if (isset($config['class']) && $this->hasItem($config['class'])) {
         $config = array_merge($config, $this->_items[$config['class']]);
     }
     return ArrayHelper::merge(['class' => 'hidev\\controllers\\CommonController'], $config);
 }
Esempio n. 26
0
 /**
  * Creates a new Rubric model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $subcategories = ArrayHelper::map(Subcategory::find()->with('englishTranslate')->all(), 'id', 'englishTranslate.title');
     $model = new Rubric();
     $enForm = new RubricTranslateForm();
     $enModel = new RubricTranslate();
     $deForm = new RubricTranslateForm();
     $deModel = new RubricTranslate();
     $post = Yii::$app->request->post();
     $translatePost = Yii::$app->request->post('RubricTranslateForm');
     $model->scenario = 'insert';
     if ($model->load($post) && $enForm->load($translatePost, 'en') && $deForm->load($translatePost, 'de')) {
         $model->image = UploadedFile::getInstance($model, 'image');
         if ($model->validate() && $enForm->validate() && $deForm->validate()) {
             $transaction = $model::getDb()->beginTransaction();
             try {
                 if ($model->save()) {
                     $model->upload();
                     $enModel->attributes = ArrayHelper::merge($enForm->attributes, ['lang' => 'en']);
                     $deModel->attributes = ArrayHelper::merge($deForm->attributes, ['lang' => 'de']);
                     $model->link('translates', $enModel);
                     $model->link('translates', $deModel);
                     $transaction->commit();
                     Yii::$app->session->setFlash('success', 'Rubric have been created.');
                 }
             } catch (\Exception $e) {
                 Yii::$app->session->setFlash('error', 'Failed to create Rubric.');
                 $transaction->rollBack();
             }
         }
     } else {
         return $this->render('create', ['model' => $model, 'enForm' => $enForm, 'deForm' => $deForm, 'subcategories' => $subcategories]);
     }
     return $this->redirect('index');
 }
Esempio n. 27
0
 public function __construct($config = [])
 {
     if (\Yii::$app->admin->requestIsAdmin) {
         $config = ArrayHelper::merge(\Yii::$app->admin->getCkeditorOptions(), $config);
     }
     parent::__construct($config);
 }
Esempio n. 28
0
 /**
  * Returns fail response
  * @param integer $code
  * @param array $data
  * @return \yii\web\Response
  */
 public static function fail($code = 400, array $data = [])
 {
     $resp = \Yii::$app->response;
     $resp->setStatusCode($code);
     $resp->data = ArrayHelper::merge(['status' => 'error', 'message' => static::$httpStatuses[$code]], $data);
     return $resp;
 }
Esempio n. 29
0
 protected function renderButtonAdd()
 {
     Html::addCssClass($this->buttonOptions, 'btn');
     $this->buttonOptions = ArrayHelper::merge($this->buttonOptions, ['role' => 'area.add', 'data-tmpl' => $this->options['id']]);
     $templateButtonAdding = strtr($this->templateButtonAdding, ['{button}' => Html::button('+', $this->buttonOptions), '{label}' => Html::tag('label', $this->label)]);
     echo Html::tag('div', $templateButtonAdding, ['class' => 'form-group']);
 }
Esempio n. 30
-1
 /**
  * Формирование Html кода поля для вывода в форме
  * @param ActiveForm $form объект форма
  * @param array $options массив html атрибутов поля
  * @param bool|int $index инднкс модели при табличном вводе
  * @return string
  */
 public function renderInput(ActiveForm $form, array $options = [], $index = false)
 {
     $options = ArrayHelper::merge($this->options, $options);
     $widgetOptions = ArrayHelper::merge(["options" => ["class" => "form-control", "prompt" => ""], "data" => $this->modelField->getDataValue()], $this->widgetOptions, ["options" => $options]);
     $attr = $this->modelField->attr;
     return $form->field($this->modelField->model, $this->getFormAttrName($index, $attr))->widget(DependDropDown::className(), $widgetOptions);
 }