File

src/app/ceph/cluster/mgr-modules/mgr-module-form/mgr-module-form.component.ts

Implements

OnInit

Metadata

selector cd-mgr-module-form
styleUrls ./mgr-module-form.component.scss
templateUrl ./mgr-module-form.component.html

Index

Properties
Methods

Constructor

constructor(route: ActivatedRoute, router: Router, formBuilder: CdFormBuilder, mgrModuleService: MgrModuleService, notificationService: NotificationService, i18n: I18n)
Parameters :
Name Type Optional
route ActivatedRoute No
router Router No
formBuilder CdFormBuilder No
mgrModuleService MgrModuleService No
notificationService NotificationService No
i18n I18n No

Methods

createForm
createForm()
Returns : void
getValidators
getValidators(moduleOption)
Parameters :
Name Optional
moduleOption No
Returns : ValidatorFn[]
goToListView
goToListView()
Returns : void
ngOnInit
ngOnInit()
Returns : void
onSubmit
onSubmit()
Returns : void

Properties

error
Default value : false
loading
Default value : false
mgrModuleForm
Type : CdFormGroup
moduleName
Type : string
Default value : ''
moduleOptions
Type : []
Default value : []
import { Component, OnInit } from '@angular/core';
import { ValidatorFn, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

import { I18n } from '@ngx-translate/i18n-polyfill';
import * as _ from 'lodash';
import { forkJoin as observableForkJoin } from 'rxjs';

import { MgrModuleService } from '../../../../shared/api/mgr-module.service';
import { NotificationType } from '../../../../shared/enum/notification-type.enum';
import { CdFormBuilder } from '../../../../shared/forms/cd-form-builder';
import { CdFormGroup } from '../../../../shared/forms/cd-form-group';
import { CdValidators } from '../../../../shared/forms/cd-validators';
import { NotificationService } from '../../../../shared/services/notification.service';

@Component({
  selector: 'cd-mgr-module-form',
  templateUrl: './mgr-module-form.component.html',
  styleUrls: ['./mgr-module-form.component.scss']
})
export class MgrModuleFormComponent implements OnInit {
  mgrModuleForm: CdFormGroup;
  error = false;
  loading = false;
  moduleName = '';
  moduleOptions = [];

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private formBuilder: CdFormBuilder,
    private mgrModuleService: MgrModuleService,
    private notificationService: NotificationService,
    private i18n: I18n
  ) {}

  ngOnInit() {
    this.route.params.subscribe(
      (params: { name: string }) => {
        this.moduleName = decodeURIComponent(params.name);
        this.loading = true;
        const observables = [];
        observables.push(this.mgrModuleService.getOptions(this.moduleName));
        observables.push(this.mgrModuleService.getConfig(this.moduleName));
        observableForkJoin(observables).subscribe(
          (resp: object) => {
            this.loading = false;
            this.moduleOptions = resp[0];
            // Create the form dynamically.
            this.createForm();
            // Set the form field values.
            this.mgrModuleForm.setValue(resp[1]);
          },
          (error) => {
            this.error = error;
          }
        );
      },
      (error) => {
        this.error = error;
      }
    );
  }

  getValidators(moduleOption): ValidatorFn[] {
    const result = [];
    switch (moduleOption.type) {
      case 'addr':
        result.push(CdValidators.ip());
        break;
      case 'uint':
      case 'int':
      case 'size':
      case 'secs':
        result.push(CdValidators.number());
        result.push(Validators.required);
        if (_.isNumber(moduleOption.min)) {
          result.push(Validators.min(moduleOption.min));
        }
        if (_.isNumber(moduleOption.max)) {
          result.push(Validators.max(moduleOption.max));
        }
        break;
      case 'str':
        if (_.isNumber(moduleOption.min)) {
          result.push(Validators.minLength(moduleOption.min));
        }
        if (_.isNumber(moduleOption.max)) {
          result.push(Validators.maxLength(moduleOption.max));
        }
        break;
      case 'float':
        result.push(Validators.required);
        result.push(CdValidators.decimalNumber());
        break;
      case 'uuid':
        result.push(CdValidators.uuid());
        break;
    }
    return result;
  }

  createForm() {
    const controlsConfig = {};
    _.forEach(this.moduleOptions, (moduleOption) => {
      controlsConfig[moduleOption.name] = [
        moduleOption.default_value,
        this.getValidators(moduleOption)
      ];
    });
    this.mgrModuleForm = this.formBuilder.group(controlsConfig);
  }

  goToListView() {
    this.router.navigate(['/mgr-modules']);
  }

  onSubmit() {
    // Exit immediately if the form isn't dirty.
    if (this.mgrModuleForm.pristine) {
      this.goToListView();
      return;
    }
    const config = {};
    _.forEach(this.moduleOptions, (moduleOption) => {
      const control = this.mgrModuleForm.get(moduleOption.name);
      // Append the option only if the value has been modified.
      if (control.dirty && control.valid) {
        config[moduleOption.name] = control.value;
      }
    });
    this.mgrModuleService.updateConfig(this.moduleName, config).subscribe(
      () => {
        this.notificationService.show(
          NotificationType.success,
          this.i18n('Updated options for module "{{name}}".', { name: this.moduleName })
        );
        this.goToListView();
      },
      () => {
        // Reset the 'Submit' button.
        this.mgrModuleForm.setErrors({ cdSubmitButton: true });
      }
    );
  }
}
<cd-loading-panel *ngIf="loading && !error"
                  i18n>Loading configuration...</cd-loading-panel>
<cd-error-panel *ngIf="loading && error"
                i18n>The configuration could not be loaded.</cd-error-panel>

<div class="col-sm-12 col-lg-6"
     *ngIf="!loading && !error">
  <form name="mgrModuleForm"
        class="form-horizontal"
        #frm="ngForm"
        [formGroup]="mgrModuleForm"
        novalidate>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title" i18n>Edit Manager module</h3>
      </div>
      <div class="panel-body">
        <div class="form-group"
             [ngClass]="{'has-error': mgrModuleForm.showError(moduleOption.value.name, frm)}"
             *ngFor="let moduleOption of moduleOptions | keyvalue">

          <!-- Field label -->
          <label class="control-label col-sm-3"
                 for="{{ moduleOption.value.name }}">
            {{ moduleOption.value.name }}
            <cd-helper *ngIf="moduleOption.value.long_desc || moduleOption.value.desc">
              {{ moduleOption.value.long_desc || moduleOption.value.desc | upperFirst }}
            </cd-helper>
          </label>

          <!-- Field control -->
          <!-- bool -->
          <div class="col-sm-7"
               *ngIf="moduleOption.value.type === 'bool'">
            <div class="checkbox checkbox-primary">
              <input id="{{ moduleOption.value.name }}"
                     type="checkbox"
                     formControlName="{{ moduleOption.value.name }}">
              <label for="{{ moduleOption.value.name }}"></label>
            </div>
          </div>

          <!-- addr|str|uuid -->
          <div class="col-sm-7"
               *ngIf="['addr', 'str', 'uuid'].includes(moduleOption.value.type)">
            <input id="{{ moduleOption.value.name }}"
                   class="form-control"
                   type="text"
                   formControlName="{{ moduleOption.value.name }}"
                   *ngIf="moduleOption.value.enum_allowed.length === 0">
            <select id="{{ moduleOption.value.name }}"
                    class="form-control"
                    formControlName="{{ moduleOption.value.name }}"
                    *ngIf="moduleOption.value.enum_allowed.length > 0">
              <option *ngFor="let value of moduleOption.value.enum_allowed"
                      [ngValue]="value">
                {{ value }}
              </option>
            </select>
            <span class="help-block"
                  *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'invalidUuid')"
                  i18n>The entered value is not a valid UUID, e.g.: 67dcac9f-2c03-4d6c-b7bd-1210b3a259a8</span>
            <span class="help-block"
                  *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'pattern')"
                  i18n>The entered value needs to be a valid IP address.</span>
          </div>

          <!-- uint|int|size|secs -->
          <div class="col-sm-7"
               *ngIf="['uint', 'int', 'size', 'secs'].includes(moduleOption.value.type)">
            <input id="{{ moduleOption.value.name }}"
                   class="form-control"
                   type="number"
                   formControlName="{{ moduleOption.value.name }}"
                   min="{{ moduleOption.value.min }}"
                   max="{{ moduleOption.value.max }}">
            <span class="help-block"
                  *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'required')"
                  i18n>This field is required.</span>
            <span class="help-block"
                  *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'max')"
                  i18n>The entered value is too high! It must be lower or equal to {{ moduleOption.value.max }}.</span>
            <span class="help-block"
                  *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'min')"
                  i18n>The entered value is too low! It must be greater or equal to {{ moduleOption.value.min }}.</span>
            <span class="help-block"
                  *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'pattern')"
                  i18n>The entered value needs to be a number.</span>
          </div>

          <!-- float -->
          <div class="col-sm-7"
               *ngIf="moduleOption.value.type === 'float'">
            <input id="{{ moduleOption.value.name }}"
                   class="form-control"
                   type="number"
                   formControlName="{{ moduleOption.value.name }}">
            <span class="help-block"
                  *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'required')"
                  i18n>This field is required.</span>
            <span class="help-block"
                  *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'pattern')"
                  i18n>The entered value needs to be a number or decimal.</span>
          </div>

        </div>
      </div>
      <div class="panel-footer">
        <div class="button-group text-right">
          <cd-submit-button type="button"
                            (submitAction)="onSubmit()"
                            [form]="mgrModuleForm">
            <ng-container i18n>Update</ng-container>
          </cd-submit-button>
          <button type="button"
                  class="btn btn-sm btn-default"
                  routerLink="/mgr-modules"
                  i18n>Back</button>
        </div>
      </div>
    </div>
  </form>
</div>

./mgr-module-form.component.scss

Legend
Html element
Component
Html element with directive

result-matching ""

    No results matching ""