/** * Позволяет тонко сконфигурировать грид перед самой отрисовкой * * @param BeforeGridEvent $event */ public function onBeforeGrid(BeforeGridEvent $event) { if (isset(Yii::app()->controller->buttons)) { foreach (Yii::app()->controller->buttons as $key => $buttonConfig) { if (isset($buttonConfig['code']) && $buttonConfig['code'] == 'create') { // Модули - типы создаваемого экземпляра $addButtonData = null; $phpScripts = PhpScript::model()->findAllByAttributes(array('id_php_script_interface' => PhpScript::ID_PHP_SCRIPT_INTERFACE_MODULE)); if (count($phpScripts) > 0) { $addButtonData = '<button class="btn navbar-btn btn-success dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>'; $addButtonData .= '<ul class="dropdown-menu">' . "\n"; foreach ($phpScripts as $phpScript) { /** * @var $phpScript PhpScript */ $linkModule = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_LIST, array(ObjectUrlRule::PARAM_OBJECT_INSTANCE => -1, ObjectUrlRule::PARAM_SYSTEM_MODULE => $phpScript->id_php_script_type)); $addButtonData .= "<li><a href='" . $linkModule . "'>" . $phpScript->description . "</a></li>"; } $addButtonData .= '</ul>' . "\n"; } $buttonConfig['addButtonData'] = $addButtonData; Yii::app()->controller->buttons[$key] = $buttonConfig; break; } } } }
public function init() { parent::init(); $data = $this->grid->dataProvider->getData(); if (count($data) == 0) { return; } $this->link = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_LIST, array(ObjectUrlRule::PARAM_OBJECT_PARENT => '{id}'), array(ObjectUrlRule::PARAM_SYSTEM_MODULE, ObjectUrlRule::PARAM_PAGER_NUM, ObjectUrlRule::PARAM_OBJECT_INSTANCE, ObjectUrlRule::PARAM_ACTION_VIEW)); $this->countData = $this->grid->dataProvider->model->getCountChildOfInstances($data); }
public function renderDataCell($row) { $data = $this->grid->dataProvider->data[$row]; $idInstance = $data->getIdInstance(); $contentCell = ''; if (in_array($idInstance, $this->_availableIdInstance)) { $link = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_LIST, array(ObjectUrlRule::PARAM_OBJECT_INSTANCE => $idInstance), array(ObjectUrlRule::PARAM_ACTION_VIEW, ObjectUrlRule::PARAM_SYSTEM_MODULE)); $contentCell = CHtml::link('', $link, array('title' => 'Изменить')); $this->htmlOptions = array('class' => 'col-ref action-edit'); } else { $contentCell = '<i></i>'; $this->htmlOptions = array('class' => 'col-ref action-edit-no', 'title' => 'Редактирование не доступно'); } echo CHtml::openTag('td', $this->htmlOptions); echo $contentCell; echo '</td>'; }
public function renderDataCell($row) { $data = $this->grid->dataProvider->data[$row]; $idInstance = $data->getIdInstance(); $contentCell = ''; if (in_array($idInstance, $this->_availableIdInstance)) { $link = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_LIST, array(ObjectUrlRule::PARAM_OBJECT_INSTANCE => $idInstance), array(ObjectUrlRule::PARAM_ACTION_VIEW, ObjectUrlRule::PARAM_SYSTEM_MODULE)); $idObject = $this->getObject()->id_object; $js = CJavaScript::encode(array('idObject' => $idObject, 'idInstance' => $idInstance, 'text' => 'Внимание! Информация будет безвозвратно удалена. Продолжить?')); $contentCell = '<a onclick="$(this).daDeleteRecord(' . $js . '); return false;" href="#" title="Удалить"></a>'; $this->htmlOptions = array('class' => 'col-ref action-delete'); } else { $contentCell = '<i></i>'; $info = isset($this->_unavailableInfo[$idInstance]) ? ', т.к. экземпляр связан с другими данными (' . $this->_unavailableInfo[$idInstance] . ')' : ''; $this->htmlOptions = array('class' => 'col-ref action-delete-no', 'title' => 'Удаление не доступно' . $info); } echo CHtml::openTag('td', $this->htmlOptions); echo $contentCell; echo '</td>'; }
public function actionIndex() { /** * @var DaActiveRecord $model * @var DaObject $object */ $object = Yii::app()->backend->object; $idObject = $object->id_object; $model = null; $id_v = HU::get(ObjectUrlRule::PARAM_ACTION_VIEW); $id = HU::post('id_instance'); if ($id == null) { $id = HU::get(ObjectUrlRule::PARAM_OBJECT_INSTANCE); } if ($id == null && $id_v == null) { throw new CHttpException(400, 'Bad Request'); } $statusProcess = intval(HU::post('submit_form', ViewController::MODE_VIEW)); if (!in_array($statusProcess, array(ViewController::MODE_VIEW, ViewController::MODE_SAVE_AND_CLOSE, ViewController::MODE_ACCEPT, ViewController::MODE_SAVE_AND_CREATE_NEW))) { throw new CHttpException(400, 'Bad Request'); } $readOnlyInstance = false; if ($id != null) { if ($id == -1) { if (!Yii::app()->authManager->canCreateInstance($idObject, Yii::app()->user->id)) { throw new CHttpException(403, 'Нет прав на создание'); } $id = null; } else { // Редактируют, проверяем доступность текущему пользователю if (!Yii::app()->authManager->checkObjectInstance(DaDbAuthManager::OPERATION_EDIT, Yii::app()->user->id, $idObject, $id)) { throw new CHttpException(403, 'Нет прав на редактирование или объект не существует'); } } } else { if ($id_v != null) { if ($id_v == -1) { throw new CHttpException(403); } else { if (!Yii::app()->authManager->checkObjectInstance(DaDbAuthManager::OPERATION_VIEW, Yii::app()->user->id, $idObject, $id_v)) { throw new CHttpException(403, "Нет прав на просмотр"); } $id = $id_v; $readOnlyInstance = true; } } } if ($id != null) { $model = $object->getModel()->findByIdInstance($id); if ($model == null) { throw new CHttpException(404); } $model->setScenario('backendUpdate'); } else { $model = $object->getModel(true); $model->setIsNewRecord(true); $model->setScenario('backendInsert'); } $visualElementArray = array(); $event = new InstanceAvailableEvent($this, $model); $this->raiseEvent(ViewController::EVENT_ON_INSTANCE_AVAILABLE, $event); $available = $event->status; if ($available == ViewController::ENTITY_STATUS_NOT_VISIBLE) { //Если нет прав на просмотр, то уходим return; // TODO } if ($available == ViewController::ENTITY_STATUS_READ_ONLY) { $readOnlyInstance = true; } $parameters = $object->parameters; foreach ($parameters as $objectParameter) { /** * @var $objectParameter ObjectParameter */ // Детальная обработка: // Если свойство является группирующем, то устанавливаем значение по умолчанию if ($model->isNewRecord && HU::get(ObjectUrlRule::PARAM_GROUP_PARAMETER) == $objectParameter->getIdParameter()) { $model->{$objectParameter->getFieldName()} = HU::get(ObjectUrlRule::PARAM_GROUP_INSTANCE); } // Установка значений свойств экземпляра по умолчанию if ($objectParameter->getType() == DataType::SEQUENCE) { if ($model->isNewRecord) { $model->{$objectParameter->getFieldName()} = 0; } } else { if ($objectParameter->getType() == DataType::ID_PARENT) { if ($model->isNewRecord) { // TODO - сделать проверку, что пользователь может создавать раздел в переданном ИД паренте $model->{$objectParameter->getFieldName()} = HU::get(ObjectUrlRule::PARAM_OBJECT_PARENT); } if ($objectParameter->getAdditionalParameter() != 1) { continue; } } } if (!$objectParameter->isVisible()) { continue; } $event = new ParameterAvailableEvent($this, $model, $objectParameter); $this->raiseEvent(ViewController::EVENT_ON_PARAMETER_AVAILABLE, $event); $availableStatus = $event->status; if ($availableStatus == ViewController::ENTITY_STATUS_NOT_VISIBLE) { //Невидим continue; } $event = new CreateVisualElementEvent($this, $model, $objectParameter); $this->raiseEvent(ViewController::EVENT_ON_CREATE_VISUAL_ELEMENT, $event); $visualElement = $event->visualElement; // Если свойство является группирующем, то пропускаем его. /*if ($visualElement == null && HU::get(ObjectUrlRule::PARAM_GROUP_PARAMETER) == $objectParameter->getIdParameter()) { $visualElement = Yii::app()->controller->createWidget('backend.widgets.hiddenField.HiddenFieldWidget', array( 'model' => $model, 'attributeName' => $objectParameter->getFieldName(), )); $visualElementArray[] = $visualElement; $model->{$objectParameter->getFieldName()} = HU::get(ObjectUrlRule::PARAM_GROUP_INSTANCE); continue; }*/ if ($visualElement == null) { $visualElement = VisualElementFactory::getVisualElement($model, $objectParameter); } if ($visualElement == null) { continue; } if ($availableStatus == ViewController::ENTITY_STATUS_READ_ONLY || $readOnlyInstance) { //Только для чтения $visualElement->setReadOnly(true); } if ($objectParameter->getFieldName() != null && $model instanceof DaInstance && $visualElement instanceof VisualElementBaseWidget) { $model->addValidator(CValidator::createValidator('safe', $model, $objectParameter->getFieldName())); } $visualElementArray[] = $visualElement; } // закончили обрабатывать свойства $modelClass = get_class($model); if (isset($_POST[$modelClass]) || isset($_POST['submit_form'])) { if (isset($_POST[$modelClass])) { $model->attributes = $_POST[$modelClass]; } $event = new PostFormEvent($this, $model); $this->raiseEvent(ViewController::EVENT_ON_POST_FORM, $event); Yii::import('ygin.modules.search.components.SearchComponent', true); if ($model->isNewRecord) { // insert if ($model->save()) { SearchComponent::replaceIndex($model); //$instance->updateObjectInstanceInfo(1); $newIdInstance = $model->getIdInstance(false); $seqKey = $object->getFieldByType(DataType::SEQUENCE); if ($seqKey != null) { $pk = $object->getFieldByType(DataType::PRIMARY_KEY); $max = Yii::app()->db->createCommand('SELECT MAX(' . $seqKey . ') FROM ' . $object->table_name)->queryScalar(); $sql = 'UPDATE ' . $object->table_name . ' SET ' . $seqKey . ' = :max WHERE ' . $pk . '=:id'; Yii::app()->db->createCommand($sql)->execute(array(':max' => $max + 1, ':id' => $newIdInstance)); } Yii::log('Добавлен новый экземпляр (' . $object->getName() . ') id=' . $newIdInstance, CLogger::LEVEL_INFO, 'backend.model.insert'); } else { $statusProcess = ViewController::MODE_ERROR; } } else { if ($model->save()) { SearchComponent::replaceIndex($model); //$instance->updateObjectInstanceInfo(2); Yii::log('Изменение (' . $object->getName() . ') id=' . $model->getIdInstance(), CLogger::LEVEL_INFO, 'backend.model.update'); } else { $statusProcess = ViewController::MODE_ERROR; } } } if ($statusProcess == ViewController::MODE_ERROR || $statusProcess == ViewController::MODE_VIEW) { $this->render('/view', array('model' => $model, 'visualElementArray' => $visualElementArray)); } else { if ($statusProcess == ViewController::MODE_ACCEPT) { $url = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_VIEW, array(ObjectUrlRule::PARAM_OBJECT_INSTANCE => $model->getIdInstance())); $this->redirect($url); } else { if ($statusProcess == ViewController::MODE_SAVE_AND_CLOSE) { $url = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_LIST, array(), array(ObjectUrlRule::PARAM_OBJECT_INSTANCE, ObjectUrlRule::PARAM_ACTION_VIEW)); $this->redirect($url); } else { if ($statusProcess == ViewController::MODE_SAVE_AND_CREATE_NEW) { $url = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_VIEW, array(ObjectUrlRule::PARAM_OBJECT_INSTANCE => -1)); $this->redirect($url); } } } } }
if (isset($button['html'])) { echo $button['html']; } else { echo CHtml::link($button['caption'], $button['url'], array('class' => 'btn navbar-btn ' . $button['class'])) . (isset($button['addButtonData']) ? $button['addButtonData'] : ''); } echo CHtml::closeTag('div'); // .btn-group } if ($searchModel != null) { Yii::app()->clientScript->registerScript('search-form-init', ' $("#' . CHtml::activeId($searchModel, 'value') . '").tooltip({ title: "Вы можете использовать <br>>, <, >=, <=, =, <> <br>в начале искомого выражения, <br>чтобы уточнить, как выполнить поиск.", html: true }); ', CClientScript::POS_READY); $form = $this->beginWidget('CActiveForm', array('id' => 'SearchForm', 'method' => 'get', 'enableAjaxValidation' => false, 'enableClientValidation' => true, 'htmlOptions' => array('class' => 'b-navbar-search navbar-form navbar-right form-inline', 'role' => 'form'), 'clientOptions' => array('validateOnSubmit' => true, 'validateOnChange' => false), 'action' => ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_LIST, array(), array(ObjectUrlRule::PARAM_OBJECT_INSTANCE)))); echo CHtml::openTag('div', array('class' => 'form-group')); echo $form->dropDownList($searchModel, 'parameter', $searchModel->toListData(), $htmlOptions = array('class' => 'fields form-control')); echo CHtml::closeTag('div'); // .form-group echo CHtml::openTag('div', array('class' => 'form-group')); echo CHtml::openTag('div', array('class' => 'input-group query-group')); echo $form->textField($searchModel, 'value', array('class' => 'query form-control', 'value' => $searchModel->value)); echo CHtml::openTag('div', array('class' => 'input-group-btn')); echo CHtml::htmlButton('<i class="glyphicon glyphicon-search"></i>', array('class' => 'btn btn-primary', 'title' => 'Найти', 'type' => 'submit')); echo CHtml::closeTag('div'); // .input-group-btn echo CHtml::closeTag('div'); // .input-group echo CHtml::closeTag('div'); // .form-group
<div class="additional-property-list">' . "\n"; } } $visualElement->run(); } } if ($isAdditionalParamExists && $isBaseParamExists) { echo " </div><!-- .additional-property-list -->\n </div><!-- .additional-property-container -->\n"; } Yii::app()->controller->layout = $layout; ?> <div class="form-actions"> <div class="bar"> <?php $link = Yii::app()->request->url; $backLink = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_LIST, array(), array(ObjectUrlRule::PARAM_OBJECT_INSTANCE, ObjectUrlRule::PARAM_ACTION_VIEW, ObjectUrlRule::PARAM_SYSTEM_MODULE)); if ($readOnlyInstance) { echo CHtml::link('Вернуться', $backLink, array('class' => 'btn btn-default')); } else { // Обработка кнопок Yii::app()->clientScript->registerScript('admin.form.init', ' $(".b-instance-edit-form .form-actions").daFixedActionBarBind(); $(".b-instance-edit-form .form-actions") .find(".btn-save").on("click", function(){ if ( !$("#aMainForm").hasClass("lock")){ var link = ""; var status = $(this).attr("data-action"); if (status == 3 || status == 5) { link = "' . $link . '"; } else if (status == 2 || status == 5) { link = "' . $link . '";
private function main() { /** * @var $model DaActiveRecord * @var $object DaObject * @var $view DaObjectView */ $object = Yii::app()->backend->object; $view = Yii::app()->backend->objectView; $model = $object->getModel(); $idObject = $object->id_object; $idView = $view->id_object_view; $this->pageDescription = $view->description; if ($this->_groupInstance != null) { $linkObject = Yii::app()->createUrl(BackendModule::ROUTE_INSTANCE_LIST, array(ObjectUrlRule::PARAM_OBJECT_PARENT => $this->_groupInstance->getIdParent(), ObjectUrlRule::PARAM_OBJECT => $this->_groupInstance->getIdObject(), ObjectUrlRule::PARAM_PAGER_NUM => ObjectUrlRule::getCurrentParameter(ObjectUrlRule::PARAM_PAGER_NUM_BACK))); //$tmpPage->setProperty(DA_URL_GO, $urlPage->GET(DA_URL_BACK_PAGE)); // TODO !!!!! $linkInstance = Yii::app()->createUrl(BackendModule::ROUTE_INSTANCE_LIST, array(ObjectUrlRule::PARAM_OBJECT_PARENT => $this->_groupInstance->getIdParent(), ObjectUrlRule::PARAM_OBJECT => $this->_groupInstance->getIdObject(), ObjectUrlRule::PARAM_OBJECT_INSTANCE => $this->_groupInstance->getIdInstance())); $caption = '"' . strip_tags($this->_groupInstance->getInstanceCaption()) . '"'; $this->caption .= ' ' . $caption; $this->breadcrumbs[$this->_groupParameter->caption] = $linkObject; $this->breadcrumbs[$caption] = $linkInstance; $this->breadcrumbs[$object->name] = '/'; } $idParent = null; $parentModel = null; $idParentField = $view->id_parent; if ($idParentField != null) { $idParent = HU::get(ObjectUrlRule::PARAM_OBJECT_PARENT); if ($idParent != null) { if (($parentModel = $model->findByPk($idParent)) == null) { $idParent = null; } else { $this->caption = $parentModel->getInstanceCaption(); $link = Yii::app()->createUrl(BackendModule::ROUTE_INSTANCE_LIST, array(ObjectUrlRule::PARAM_OBJECT_PARENT => $parentModel->{$idParentField}, ObjectUrlRule::PARAM_OBJECT_VIEW => $idView, ObjectUrlRule::PARAM_OBJECT => $idObject)); $this->buttons[] = array('url' => $link, 'caption' => '<i class="glyphicon glyphicon-arrow-up icon-white"></i> Вверх', 'class' => 'btn-primary'); $this->breadcrumbs = array(); $tmp = $parentModel; while ($tmp != null) { $link = Yii::app()->createUrl(BackendModule::ROUTE_INSTANCE_LIST, array(ObjectUrlRule::PARAM_OBJECT_PARENT => $tmp->{$idParentField}, ObjectUrlRule::PARAM_OBJECT_VIEW => $idView, ObjectUrlRule::PARAM_OBJECT => $idObject)); $this->breadcrumbs[$tmp->getInstanceCaption()] = $link; if ($tmp->{$idParentField} != null) { $tmp = $model->findByPk($tmp->{$idParentField}); } else { $tmp = null; } } $this->breadcrumbs[$object->name] = Yii::app()->createUrl(BackendModule::ROUTE_INSTANCE_LIST, array(ObjectUrlRule::PARAM_OBJECT_VIEW => $idView, ObjectUrlRule::PARAM_OBJECT => $idObject)); $this->breadcrumbs = array_reverse($this->breadcrumbs); } } } // вновь восстанавливаем чистую модель, т.к. конструкции типа $model->findByPk затирают resetScope $model = $object->getModel(); // кнопка создать if (Yii::app()->authManager->canCreateInstance($idObject, Yii::app()->user->id)) { $link = ObjectUrlRule::createUrlFromCurrent(BackendModule::ROUTE_INSTANCE_LIST, array(ObjectUrlRule::PARAM_OBJECT_INSTANCE => -1)); array_unshift($this->buttons, array('url' => $link, 'caption' => '<i class="glyphicon glyphicon-plus icon-white"></i> Создать', 'class' => 'btn-success', 'code' => 'create')); } $dataProvider = $this->buildDataProvider($view, $model); $criteria = $dataProvider->getCriteria(); // поиск $searchModel = new ParameterSearchForm($object); foreach ($searchModel->getSearchParameters() as $searchParam) { $event = new ParameterAvailableToSearchEvent($this, $searchParam->parameter); $this->raiseEvent(DefaultController::EVENT_ON_PARAMETER_AVAILABLE_TO_SEARCH, $event); $searchParam->visible = $event->visible; } if (isset($_GET['ParameterSearchForm'])) { $searchModel->attributes = $_GET['ParameterSearchForm']; } else { if (isset($_GET['ParameterSearchForm[parameter]']) && isset($_GET['ParameterSearchForm[value]'])) { $searchModel->parameter = $_GET['ParameterSearchForm[parameter]']; $searchModel->value = $_GET['ParameterSearchForm[value]']; } } $searchActive = false; if ($searchModel->getHasVisibleSearchParameters()) { $this->searchModel = $searchModel; // Условия поиска по параметрам: if ($this->searchModel->validate() && $this->searchModel->value != null) { $searchActive = true; $searchCriteria = $this->searchModel->getSearchCriteria(); $criteria->mergeWith($searchCriteria); } } // условие по родителю if (!$searchActive && $this->getGroupInstance() == null && $idParentField != null) { if ($idParent == null) { $criteria->addCondition($idParentField . " IS NULL"); } else { $criteria->addCondition($idParentField . " = :id_parent"); $criteria->params[':id_parent'] = $idParent; } } else { if ($this->getGroupInstance() != null) { // Добавляем ограничения по подчинённым сущностям. $criteria->addCondition("t." . $this->getGroupParameter()->getFieldName() . " = :group_instance"); $criteria->params[':group_instance'] = $this->getGroupInstance()->getIdInstance(); } } // сортировка путем перемещения строк таблицы $seqKey = null; // если идет поиск, то отключаем сотрировку перетаскиваением if (!$searchActive && ($seqKey = $object->getParameterObjectByField($object->getFieldByType(DataType::SEQUENCE))) != null) { $event = new ParameterAvailableEvent($this, $model, $seqKey); $event->params = array('mode' => 'seqKey'); $this->raiseEvent(ViewController::EVENT_ON_PARAMETER_AVAILABLE, $event); if ($event->status != ViewController::ENTITY_STATUS_AVAILABLE) { $seqKey = null; } } // сортировка грида $oby = $view->getOrderBy(); if ($oby == null && $object->id_field_order != null) { //Если есть порядок сортировки, то добавляем сортировку //Загружаем информацию по св-ву сортировки: $op = $object->getParameterObjectByIdParameter($object->id_field_order); $name = "t." . $op->getFieldName(); $direction = $object->order_type; if ($direction == 1) { $direction = "ASC"; } else { if ($direction == 2) { $direction = "DESC"; } } $oby = $name . " " . $direction; } $sort = new BackendSort(); $sort->attributes = $model->attributeNames(); $sort->model = $model; $sort->params = array_merge(ObjectUrlRule::getCurrentParams(), HU::arrayToQueryArray('ParameterSearchForm', HU::get('ParameterSearchForm', array()))); $sort->defaultOrder = $oby; $dataProvider->sort = $sort; // $instanceQuery->setFrom($objectRazdel->getFrom()); // TODO ??? // пагинатор $withSwitchPages = $seqKey == null; // если есть сортировка на странице, то не выводим переключатель страниц $paginatorConfig = $withSwitchPages ? array('pageSize' => $view->getCountData(), 'pageVar' => 'go', 'params' => array_merge(ObjectUrlRule::getCurrentParams(), HU::arrayToQueryArray('ParameterSearchForm', HU::get('ParameterSearchForm', array())))) : false; $dataProvider->pagination = $paginatorConfig; Yii::import('backend.components.column.*'); $gridColumns = array(); $pk = $model->getInstanceKeyName(); // колонка с ид объекта $gridColumns[] = array('name' => $pk, 'header' => 'id', 'htmlOptions' => array('class' => 'col-id')); // колонка сортировки if ($seqKey != null) { $isSortAjax = $sort->defaultOrder == $sort->getOrderBy(); if ($isSortAjax) { $gridColumns[] = array('sortable' => false, 'header' => ' ', 'type' => 'raw', 'value' => '\'<i class="glyphicon glyphicon-resize-vertical"></i>\'', 'htmlOptions' => array('class' => 'col-num sorter', 'title' => 'Перетащите элемент для изменения последовательности')); Yii::app()->clientScript->registerScript('admin.sequence-order.init_client', '$(".b-instance-list").daInstanceSequence(' . CJavaScript::encode(array('idObject' => $idObject, 'isAjax' => $isSortAjax)) . ');', CClientScript::POS_READY); $js = 'function da_sortInstances(idObject, m_seq) { ' . CHtml::ajax(array('type' => 'POST', 'dataType' => 'json', 'url' => Yii::app()->createUrl('backend/ygin/sort'), 'data' => 'js:{idObject:idObject, data:m_seq}', 'success' => 'function(data){if (data.error !== undefined) {$.daSticker({text:data.error, type:"error"}); return;} $.daSticker({text:data.message, type:"success"}); }')) . ' }'; Yii::app()->clientScript->registerScript('admin.sequence-order.init_server', $js, CClientScript::POS_HEAD); } //$gridColumns[] = array('class'=>'backend.components.column.SortColumn'); /* $daPage->addIdAjax(DA_AJAX_SORT_INSTANCES); if (!$isSortAjax) { $this->buttons[] = array( 'html' => '<button class="btn btn-default" onclick="$(\".b-instance-list\").daUpdateSequence({\"idObject\":'.$idObject.', \"isNotify\":true});"><i class="glyphicon glyphicon-indent-right"></i> Упорядочить</button>', ); } */ } // пустая колонка (верстка) $gridColumns[] = array('sortable' => false, 'header' => ' ', 'type' => 'raw', 'value' => '\' \'', 'headerHtmlOptions' => array('class' => 'col-void')); // колонки представлений $columns = $view->columns; $selectFields = array(); foreach ($columns as $column) { if ($column->getIdObjectParameter() != null) { $objParam = $view->object->getParameterObjectByIdParameter($column->getIdObjectParameter()); if ($objParam != null) { $selectFields[] = $objParam->getFieldName(); } } // Если у отображаемого объекта есть группирующее свойство, то колонку для него пропускаем. if ($this->getGroupParameter() != null && $this->getGroupParameter()->getIdParameter() == $column->getIdObjectParameter()) { continue; } $header = $column->getCaption(); $columnConfig = array('sortable' => $header == null ? false : true, 'class' => 'BaseColumn', 'header' => $header === null ? '' : $header, 'name' => $column->getField(), 'object' => $object, 'objectParameter' => $column->getIdObjectParameter() == null ? null : $object->getParameterObjectByIdParameter($column->getIdObjectParameter())); $phpScript = $column->getIdPhpScript() == null ? null : ($phpScript = $column->columnClass); if ($phpScript == null) { $type = $column->getType(); switch ($type) { case DataType::BOOLEAN: $columnConfig['class'] = 'BooleanColumn'; break; case DataType::FILE: $columnConfig['class'] = 'FileColumn'; break; case DataType::OBJECT: $columnConfig['class'] = 'ObjectColumn'; break; case DataType::REFERENCE: $columnConfig['class'] = 'ReferenceColumn'; break; case DataType::TIMESTAMP: $columnConfig['htmlOptions'] = array('class' => 'col-num'); $columnConfig['type'] = 'datetime'; if ($column->getIdObjectParameter() != null) { $objParam = $view->object->getParameterObjectByIdParameter($column->getIdObjectParameter()); if ($objParam != null && intval($objParam->getAdditionalParameter()) === 1) { $columnConfig['type'] = 'date'; } } break; case DataType::TEXTAREA: $columnConfig['type'] = 'Ntext'; break; case DataType::INT: case DataType::VARCHAR: case DataType::EDITOR: $columnConfig['type'] = 'text'; break; default: throw new Exception("Для колонки (id=" . $column->getIdColumn() . ") c типом=" . $type . " не определен класс-обработчик"); } } else { $columnConfig['class'] = $phpScript->file_path; } $gridColumns[] = $columnConfig; } $select = $pk . (count($selectFields) > 0 ? ', ' . implode(',', $selectFields) : ''); if ($view->getSelect() != null) { $select .= ', ' . $view->getSelect(); } if ($view->id_parent != null) { $select .= ',' . $view->id_parent; } $criteria->select = $select; // колонка со связями // Подчинённые объекты $relationParams = $object->relationParameters; // Узнаём о том, может ли пользователь работать хотя бы с одним дочерним объектом: $isChildDataAvailable = false; $tmpIdObject = null; foreach ($relationParams as $parameter) { if ($parameter->isRelation() == false) { continue; } $idObjectTmp = $parameter->getIdObjectParameter(); if ($idObjectTmp == $tmpIdObject) { continue; } if (Yii::app()->authManager->checkObject(DaDbAuthManager::OPERATION_LIST, Yii::app()->user->id, $idObjectTmp)) { $isChildDataAvailable = true; break; } $tmpIdObject = $idObjectTmp; } if (count($relationParams) > 0 && $isChildDataAvailable) { $gridColumns[] = array('class' => 'RelationsColumn', 'childData' => $relationParams, 'object' => $object); } // Зайти в папку if ($view->id_parent != null && $this->getGroupInstance() == null) { $gridColumns[] = array('class' => 'FolderColumn', 'parentField' => $view->id_parent); } $gridColumns[] = array('class' => 'ActionViewColumn', 'object' => $object); $gridColumns[] = array('class' => 'ActionUpdateColumn', 'object' => $object); $gridColumns[] = array('class' => 'ActionDeleteColumn', 'object' => $object); Yii::import('zii.widgets.grid.CGridView', true); $grid = Yii::app()->getWidgetFactory()->createWidget($this, 'CGridView', array('dataProvider' => $dataProvider, 'columns' => $gridColumns, 'pager' => array('class' => 'LinkPagerWidget', 'pagerCssClass' => '', 'firstPageLabel' => '<i class="glyphicon glyphicon-chevron-left"></i>', 'lastPageLabel' => '<i class="glyphicon glyphicon-chevron-right"></i>', 'htmlOptions' => array('class' => 'yiiPager pagination pagination-sm')), 'enablePagination' => $withSwitchPages, 'summaryCssClass' => 'b-instance-list-count', 'pagerCssClass' => 'b-pagination-container', 'cssFile' => false, 'itemsCssClass' => 'table table-bordered b-instance-list daGallery', 'rowCssClass' => array('base', 'alt'), 'template' => "{summary}{pager}\n{items}\n{summary}{pager}", 'beforeAjaxUpdate' => 'function(){$(document).trigger("beforeGridUpdate") }', 'afterAjaxUpdate' => 'function(){$(document).trigger("afterGridUpdate") }', 'rowHtmlOptionsExpression' => 'array("id" => "ygin_inst_".$data->getIdInstance());')); Yii::app()->clientScript->registerScript('admin.paginator.init', ' $(document).on("afterGridUpdate", function(e) { $(".pagination .b-ajax-process").removeClass("b-ajax-process-active"); }); $(document).on("beforeGridUpdate", function(e) { $(".pagination .b-ajax-process").addClass("b-ajax-process-active"); }); ', CClientScript::POS_READY); $event = new BeforeGridEvent($this, $idView, $grid); $this->raiseEvent(DefaultController::EVENT_ON_BEFORE_GRID, $event); $this->render('/index', array('grid' => $grid)); }