예제 #1
0
 /**
  * Retrieves form fields configuration. Fields can be config arrays, ActiveField objects or closures.
  *
  * @param \yii\base\Model|\netis\crud\db\ActiveRecord $model
  * @param array           $fields
  * @param bool            $multiple         true for multiple values inputs, usually used for search forms
  * @param array           $hiddenAttributes list of attribute names to render as hidden fields
  *
  * @return array form fields
  * @throws InvalidConfigException
  */
 public static function getFormFields($model, $fields, $multiple = false, $hiddenAttributes = [])
 {
     if (!$model instanceof \yii\db\ActiveRecord) {
         return $model->safeAttributes();
     }
     $keys = Action::getModelKeys($model);
     $hiddenAttributes = array_flip($hiddenAttributes);
     list($behaviorAttributes, $blameableAttributes) = Action::getModelBehaviorAttributes($model);
     $attributes = $model->safeAttributes();
     $relations = $model->relations();
     if (($versionAttribute = $model->optimisticLock()) !== null) {
         $hiddenAttributes[$versionAttribute] = true;
     }
     $formFields = [];
     foreach ($fields as $key => $field) {
         if ($field instanceof ActiveField) {
             $formFields[$key] = $field;
             continue;
         } elseif (!is_string($field) && is_callable($field)) {
             $formFields[$key] = call_user_func($field, $model);
             if (!is_string($formFields[$key])) {
                 throw new InvalidConfigException('Field definition must be either an ActiveField or a callable.');
             }
             continue;
         } elseif (!is_string($field)) {
             throw new InvalidConfigException('Field definition must be either an ActiveField or a callable.');
         }
         $attributeName = Html::getAttributeName($field);
         if (in_array($attributeName, $relations)) {
             $formFields = static::addRelationField($formFields, $model, $field, $hiddenAttributes, $attributes, $multiple);
         } elseif (in_array($attributeName, $attributes)) {
             if (in_array($attributeName, $keys) || in_array($attributeName, $behaviorAttributes)) {
                 continue;
             }
             $formFields = static::addFormField($formFields, $model, $field, $hiddenAttributes, $multiple);
         }
     }
     return $formFields;
 }
예제 #2
0
 public function behaviors()
 {
     return array_merge(parent::behaviors(), ['labels' => ['class' => 'netis\\crud\\db\\LabelsBehavior', 'attributes' => ['ProductName'], 'crudLabels' => ['default' => Yii::t('app', 'Product'), 'relation' => Yii::t('app', 'Products'), 'index' => Yii::t('app', 'Browse Products'), 'create' => Yii::t('app', 'Create Product'), 'read' => Yii::t('app', 'View Product'), 'update' => Yii::t('app', 'Update Product'), 'delete' => Yii::t('app', 'Delete Product')]]]);
 }
예제 #3
0
 /**
  * Sets a flash message and configures response headers.
  * @param ActiveRecord $model
  * @param bool $wasNew
  */
 protected function afterSave($model, $wasNew)
 {
     if ($wasNew) {
         $message = Yii::t('app', '<strong>Success!</strong> A new record has been created.');
     } else {
         $message = Yii::t('app', '<strong>Success!</strong> Record has been updated.');
     }
     if (!isset($_POST[self::NEW_RELATED_BUTTON_NAME])) {
         $this->setFlash('success', $message);
     }
     $id = $this->exportKey($model->getPrimaryKey(true));
     $response = Yii::$app->getResponse();
     $response->setStatusCode(201);
     if (!Yii::$app->request->isAjax) {
         // when such header is set, ActiveController will change the response code set above to a redirect
         $response->getHeaders()->set('Location', isset($_POST[self::NEW_RELATED_BUTTON_NAME]) ? Url::current(['id' => $id, self::ADD_RELATED_NAME => $_POST[self::NEW_RELATED_BUTTON_NAME]], true) : Url::toRoute([$this->viewAction, 'id' => $id], true));
     }
     $response->getHeaders()->set('X-Primary-Key', $id);
 }
예제 #4
0
 /**
  * Builds an array containing all possible status changes and result of validating every transition.
  * @param \netis\crud\db\ActiveRecord|IStateful $model
  * @return array
  */
 public function prepareStates($model)
 {
     $checkedAccess = [];
     $result = [];
     $attribute = $model->stateAttributeName;
     $sourceState = $model->getAttribute($attribute);
     foreach ($model->getTransitionsGroupedByTarget() as $targetState => $target) {
         $state = $target['state'];
         $sources = $target['sources'];
         if (!isset($sources[$sourceState])) {
             continue;
         }
         $enabled = null;
         $sourceStateObject = $sources[$sourceState];
         $authItem = $sourceStateObject->auth_item_name;
         if (trim($authItem) === '') {
             $checkedAccess[$authItem] = true;
         } elseif (!isset($checkedAccess[$authItem])) {
             $checkedAccess[$authItem] = Yii::$app->user->can($authItem, ['model' => $model]);
         }
         $enabled = ($enabled === null || $enabled) && $checkedAccess[$authItem];
         $valid = !$enabled || $model->isTransitionAllowed($targetState);
         $entry = ['post' => $state->post_label, 'label' => $sources[$sourceState]->label, 'icon' => $state->icon, 'class' => $state->css_class, 'target' => $targetState, 'enabled' => $enabled && $valid, 'valid' => $valid, 'url' => Url::toRoute([$this->id, $this->getUrlParams($state, $model, $targetState, $this->id)])];
         if ($state->display_order) {
             $result[$state->display_order] = $entry;
         } else {
             $result[] = $entry;
         }
     }
     ksort($result);
     return $result;
 }
예제 #5
0
 public function setSuccessMessage(ActiveRecord $model, $skippedModels, $failedModels, $successModels)
 {
     $message = Yii::t('netis/fsm/app', '{number} out of {total} {model} has been successfully updated.', ['number' => count($successModels), 'total' => count($successModels) + count($failedModels) + count($skippedModels), 'model' => $model->getCrudLabel('relation')]);
     if (count($successModels) > 0) {
         $this->setFlash($this->postFlashKey, $message);
     }
     if (count($failedModels) === 0) {
         return;
     }
     $errorMessage = '';
     foreach ($failedModels as $label => $errors) {
         $errorMessage .= Html::tag('li', $label . ':&nbsp;' . $errors);
     }
     $errorMessage = Html::tag('ul', $errorMessage);
     $this->setFlash('error', Yii::t('netis/fsm/app', 'Failed to change status for following orders: ') . $errorMessage);
 }
 public function behaviors()
 {
     return array_merge(parent::behaviors(), ['labels' => ['class' => 'netis\\crud\\db\\LabelsBehavior', 'attributes' => ['CustomerTypeID'], 'crudLabels' => ['default' => Yii::t('app', 'Customer Demographic'), 'relation' => Yii::t('app', 'Customer Demographics'), 'index' => Yii::t('app', 'Browse Customer Demographics'), 'create' => Yii::t('app', 'Create Customer Demographic'), 'read' => Yii::t('app', 'View Customer Demographic'), 'update' => Yii::t('app', 'Update Customer Demographic'), 'delete' => Yii::t('app', 'Delete Customer Demographic')]]]);
 }
예제 #7
0
 /**
  * @param \yii\base\Action $action
  * @param ActiveRecord $model
  * @param bool $horizontal
  * @param array $privs
  * @param array $defaultActions
  * @param array $confirms
  * @return array
  */
 public function getMenuCurrent(\yii\base\Action $action, $model, $horizontal, $privs, $defaultActions, $confirms)
 {
     $menu = [];
     $id = null;
     if (!$model->isNewRecord) {
         $id = $action instanceof Action ? $action->exportKey($model->getPrimaryKey(true)) : implode(';', $model->getPrimaryKey(true));
     }
     if ($privs['read'] && $defaultActions['history'] && (!$model->isNewRecord || $action->id === 'update') && $model->getBehavior('trackable') !== null) {
         $menu['history'] = ['label' => Yii::t('app', 'History of changes'), 'icon' => 'list-alt', 'url' => array_merge(['history', 'id' => $id], $this->getUrlParams('history', $id))];
     }
     if (!$horizontal && $model->isNewRecord) {
         return $menu;
     }
     if ($privs['update'] && ($horizontal || $action->id !== 'update')) {
         $menu['update'] = ['label' => Yii::t('app', 'Update'), 'icon' => 'pencil', 'url' => array_merge(['update', 'id' => $id], $this->getUrlParams('update', $id)), 'active' => $action->id === 'update' && !$model->isNewRecord];
     }
     if ($privs['read'] && $defaultActions['view'] && ($horizontal || $action->id !== 'view')) {
         $menu['view'] = ['label' => Yii::t('app', 'View'), 'icon' => 'eye-open', 'url' => array_merge(['view', 'id' => $id], $this->getUrlParams('view', $id)), 'linkOptions' => $action->id === 'view' ? [] : ['data-confirm' => $confirms['leave']], 'active' => $action->id === 'view'];
     }
     if ($privs['read'] && $defaultActions['print'] && ($horizontal || $action->id !== 'print')) {
         $menu['print'] = ['label' => Yii::t('app', 'Print'), 'icon' => 'print', 'url' => array_merge(['print', 'id' => $id, '_format' => 'pdf'], $this->getUrlParams('print', $id)), 'linkOptions' => $action->id === 'print' ? [] : ['data-confirm' => $confirms['leave']], 'active' => $action->id === 'print'];
     }
     if ($privs['delete']) {
         $menu['delete'] = ['label' => Yii::t('app', 'Delete'), 'icon' => 'trash', 'url' => array_merge(['delete', 'id' => $id], $this->getUrlParams('delete', $id)), 'linkOptions' => ['data-confirm' => $confirms['delete'], 'data-method' => 'post']];
     }
     if ($privs['toggle']) {
         $enabled = !$model->isNewRecord && $model->getIsEnabled();
         $menu['toggle'] = ['label' => $enabled ? Yii::t('app', 'Disable') : Yii::t('app', 'Enable'), 'icon' => $enabled ? 'ban' : 'reply', 'url' => array_merge(['toggle', 'id' => $id], $this->getUrlParams('toggle', $id)), 'linkOptions' => $enabled ? ['data-confirm' => $confirms['disable']] : []];
     }
     if (!$model->isNewRecord && class_exists('netis\\fsm\\components\\StateAction') && $model instanceof \netis\fsm\components\IStateful && $privs['state']) {
         $controllerActions = $this->owner->actions();
         $action = null;
         if (isset($controllerActions['state'])) {
             $action = Yii::createObject($controllerActions['state'], ['state', $this->owner]);
         }
         if ($action === null || !$action instanceof StateActionInterface) {
             $action = Yii::createObject(\netis\fsm\components\StateAction::className(), ['state', $this->owner]);
         }
         $transitions = $model->getTransitionsGroupedByTarget();
         $stateAttribute = $model->getStateAttributeName();
         $stateMenu = $action->getContextMenuItem('state', $transitions, $model, $model->{$stateAttribute}, [$this->owner, 'hasAccess'], $this->useDropDownMenuForTransitions);
         //if label is set then it's drop down menu
         //todo set active item for buttons
         if (isset($stateMenu['label']) && $action->id === 'state') {
             $stateMenu['active'] = true;
         }
         $menu = array_merge($menu, $stateMenu);
     }
     foreach ($menu as $key => $item) {
         if ($model->isNewRecord) {
             $menu[$key]['disabled'] = true;
         }
     }
     return $menu;
 }
예제 #8
0
 /**
  * @param ActiveRecord $model
  * @param Query $query
  * @return ActiveDataProvider
  */
 public function getDataProvider(ActiveRecord $model, Query $query)
 {
     return new ActiveDataProvider(['query' => $query, 'pagination' => false, 'sort' => ['defaultOrder' => array_fill_keys($model->primaryKey(), SORT_ASC)]]);
 }
예제 #9
0
 /**
  * @param ActiveRecord $model
  * @param string $field relation name
  * @param ActiveQuery $relation
  * @return array grid column definition
  */
 protected static function getRelationColumn($model, $field, $relation)
 {
     return ['attribute' => $field, 'format' => ['crudLink', ['data-pjax' => '0']], 'visible' => true, 'label' => $model->getRelationLabel($relation, $field)];
 }
예제 #10
0
 public function behaviors()
 {
     return array_merge(parent::behaviors(), ['labels' => ['class' => 'netis\\crud\\db\\LabelsBehavior', 'attributes' => ['TerritoryID'], 'crudLabels' => ['default' => Yii::t('app', 'Employee Territory'), 'relation' => Yii::t('app', 'Employee Territories'), 'index' => Yii::t('app', 'Browse Employee Territories'), 'create' => Yii::t('app', 'Create Employee Territory'), 'read' => Yii::t('app', 'View Employee Territory'), 'update' => Yii::t('app', 'Update Employee Territory'), 'delete' => Yii::t('app', 'Delete Employee Territory')]]]);
 }