Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Feature/36382 improvements (#9266)

Aleix Suau4700b77033c0
diff --git a/config/locales/js-en.yml b/config/locales/js-en.yml
index 103783586e4..c5f774cdae8 100644
--- a/config/locales/js-en.yml
+++ b/config/locales/js-en.yml
@@ -1000,6 +1000,7 @@ en:
notice_successful_create: "Successful creation."
notice_successful_delete: "Successful deletion."
notice_successful_update: "Successful update."
+ notice_job_started: "job started."
notice_bad_request: "Bad Request."
relations:
diff --git a/frontend/src/app/components/work-packages/work-package-comment/wp-comment-field.component.ts b/frontend/src/app/components/work-packages/work-package-comment/wp-comment-field.component.ts
index df22c757ba6..81aedc9a32a 100644
--- a/frontend/src/app/components/work-packages/work-package-comment/wp-comment-field.component.ts
+++ b/frontend/src/app/components/work-packages/work-package-comment/wp-comment-field.component.ts
@@ -30,12 +30,11 @@ import { ConfigurationService } from 'core-app/modules/common/config/configurati
import { Component, OnInit } from "@angular/core";
import {
FormattableEditFieldComponent,
- formattableFieldTemplate
} from "core-app/modules/fields/edit/field-types/formattable-edit-field/formattable-edit-field.component";
import { InjectField } from "core-app/helpers/angular/inject-field.decorator";
@Component({
- template: formattableFieldTemplate
+ templateUrl: "../../../modules/fields/edit/field-types/formattable-edit-field/formattable-edit-field.component.html"
})
export class WorkPackageCommentFieldComponent extends FormattableEditFieldComponent implements OnInit {
public isBusy = false;
@@ -49,6 +48,5 @@ export class WorkPackageCommentFieldComponent extends FormattableEditFieldCompon
ngOnInit() {
super.ngOnInit();
- this.rawValue = this.rawValue || '';
}
}
diff --git a/frontend/src/app/core/services/forms/forms.service.spec.ts b/frontend/src/app/core/services/forms/forms.service.spec.ts
index 6b3393b47dc..0457ba9a654 100644
--- a/frontend/src/app/core/services/forms/forms.service.spec.ts
+++ b/frontend/src/app/core/services/forms/forms.service.spec.ts
@@ -74,7 +74,7 @@ describe('FormsService', () => {
it('should format the model to fit the backend expectation', () => {
// @ts-ignore
- const formattedModel = service._formatModelToSubmit(formModel);
+ const formattedModel = service.formatModelToSubmit(formModel);
const expectedResult = {
"name": "Project 1",
"_links": {
@@ -130,7 +130,7 @@ describe('FormsService', () => {
};
// @ts-ignore
- service._handleBackendFormValidationErrors(backEndErrorResponse, form);
+ service.handleBackendFormValidationErrors(backEndErrorResponse, form);
expect(form.get('name')!.invalid).toBe(true);
expect(form.get('_links')!.get('parent')!.invalid).toBe(true);
diff --git a/frontend/src/app/core/services/forms/forms.service.ts b/frontend/src/app/core/services/forms/forms.service.ts
index 39e8b64ef3a..3cd79bcfc21 100644
--- a/frontend/src/app/core/services/forms/forms.service.ts
+++ b/frontend/src/app/core/services/forms/forms.service.ts
@@ -14,7 +14,7 @@ export class FormsService {
) { }
submit$(form:FormGroup, resourceEndpoint:string, resourceId?:string, formHttpMethod?: 'post' | 'patch'):Observable<any> {
- const modelToSubmit = this._formatModelToSubmit(form.value);
+ const modelToSubmit = this.formatModelToSubmit(form.getRawValue());
const httpMethod = resourceId ? 'patch' : (formHttpMethod || 'post');
const url = resourceId ? `${resourceEndpoint}/${resourceId}` : resourceEndpoint;
@@ -30,7 +30,7 @@ export class FormsService {
.pipe(
catchError((error:HttpErrorResponse) => {
if (error.status == 422 ) {
- this._handleBackendFormValidationErrors(error, form);
+ this.handleBackendFormValidationErrors(error, form);
}
throw error;
@@ -39,7 +39,7 @@ export class FormsService {
}
validateForm$(form:FormGroup, resourceEndpoint:string):Observable<any> {
- const modelToSubmit = this._formatModelToSubmit(form.value);
+ const modelToSubmit = this.formatModelToSubmit(form.value);
return this._httpClient
.post(
@@ -51,13 +51,13 @@ export class FormsService {
}
)
.pipe(
- map((response: HalSource) => this._getFormattedErrors(Object.values(response?._embedded?.validationErrors))),
- map((formattedErrors: IFormattedValidationError[]) => this._setFormValidationErrors(formattedErrors, form)),
+ map((response: HalSource) => this.getFormattedErrors(Object.values(response?._embedded?.validationErrors))),
+ map((formattedErrors: IFormattedValidationError[]) => this.setFormValidationErrors(formattedErrors, form)),
);
}
getFormBackendValidationError$(formValue: {[key:string]: any}, resourceEndpoint:string, limitValidationToKeys?:string | string[]) {
- const modelToSubmit = this._formatModelToSubmit(formValue);
+ const modelToSubmit = this.formatModelToSubmit(formValue);
return this._httpClient
.post(
@@ -72,11 +72,11 @@ export class FormsService {
}
)
.pipe(
- map((response: HalSource) => this._getAllFormValidationErrors(response._embedded.validationErrors, limitValidationToKeys))
+ map((response: HalSource) => this.getAllFormValidationErrors(response._embedded.validationErrors, limitValidationToKeys))
);
}
- private _formatModelToSubmit(formModel:IOPFormModel):IOPFormModel {
+ private formatModelToSubmit(formModel:IOPFormModel):IOPFormModel {
const resources = formModel?._links || {};
const formattedResources = Object
@@ -101,15 +101,15 @@ export class FormsService {
}
}
- private _handleBackendFormValidationErrors(error:HttpErrorResponse, form:FormGroup):void {
+ private handleBackendFormValidationErrors(error:HttpErrorResponse, form:FormGroup):void {
const errors:IOPFormError[] = error?.error?._embedded?.errors ?
error?.error?._embedded?.errors : [error.error];
- const formErrors = this._getFormattedErrors(errors);
+ const formErrors = this.getFormattedErrors(errors);
- this._setFormValidationErrors(formErrors, form);
+ this.setFormValidationErrors(formErrors, form);
}
- private _setFormValidationErrors(errors:IFormattedValidationError[], form:FormGroup) {
+ private setFormValidationErrors(errors:IFormattedValidationError[], form:FormGroup) {
errors.forEach((err:any) => {
const formControl = form.get(err.key) || form.get('_links')?.get(err.key);
@@ -117,10 +117,10 @@ export class FormsService {
});
}
- private _getAllFormValidationErrors(validationErrors:IOPValidationErrors, formControlKeys?:string | string[]): {[key:string]: {message:string}} {
+ private getAllFormValidationErrors(validationErrors:IOPValidationErrors, formControlKeys?:string | string[]): {[key:string]: {message:string}} {
const errors = Object.values(validationErrors);
const keysToValidate = Array.isArray(formControlKeys) ? formControlKeys : [formControlKeys];
- const formErrors = this._getFormattedErrors(errors)
+ const formErrors = this.getFormattedErrors(errors)
.filter(error => {
if (!formControlKeys) {
return true;
@@ -138,7 +138,7 @@ export class FormsService {
return formErrors
}
- private _getFormattedErrors(errors:IOPFormError[]):IFormattedValidationError[] {
+ private getFormattedErrors(errors:IOPFormError[]):IFormattedValidationError[] {
const formattedErrors = errors.map(err => ({
key: err._embedded.details.attribute,
message: err.message
diff --git a/frontend/src/app/core/services/forms/typings.d.ts b/frontend/src/app/core/services/forms/typings.d.ts
index 0a712bc83a0..c09298360b9 100644
--- a/frontend/src/app/core/services/forms/typings.d.ts
+++ b/frontend/src/app/core/services/forms/typings.d.ts
@@ -1,38 +1,38 @@
interface IOPFormSettingsResource {
- _type?: "Form";
- _embedded: IOPFormSettings;
- _links?: {
- self: IOPApiCall;
- validate: IOPApiCall;
- commit: IOPApiCall;
- previewMarkup?: IOPApiCall;
+ _type?:"Form";
+ _embedded:IOPFormSettings;
+ _links?:{
+ self:IOPApiCall;
+ validate:IOPApiCall;
+ commit:IOPApiCall;
+ previewMarkup?:IOPApiCall;
};
}
interface IOPFormSettings {
- payload: IOPFormModel;
- schema: IOPFormSchema;
- validationErrors?: IOPValidationErrors;
+ payload:IOPFormModel;
+ schema:IOPFormSchema;
+ validationErrors?:IOPValidationErrors;
[nonUsedSchemaKeys:string]:any,
}
interface IOPFormSchema {
- _type?: "Schema";
- _dependencies?: unknown[];
- _attributeGroups?: IOPAttributeGroup[];
- lockVersion?: IOPFieldSchema;
- [fieldKey: string]: IOPFieldSchema | any;
- _links?: {
- baseSchema?: {
- href: string;
+ _type?:"Schema";
+ _dependencies?:unknown[];
+ _attributeGroups?:IOPAttributeGroup[];
+ lockVersion?:number;
+ [fieldKey:string]:IOPFieldSchema | any;
+ _links?:{
+ baseSchema?:{
+ href:string;
};
};
}
interface IOPFormModel {
- [key: string]: string | number | Object | HalLinkSource | null | undefined;
- _links?: {
- [key: string]: IOPFieldModel | IOPFieldModel[] | null;
+ [key:string]:string | number | Object | HalLinkSource | null | undefined;
+ _links?:{
+ [key:string]:IOPFieldModel | IOPFieldModel[] | null;
};
_meta?:{
[key:string]:string|number|Object|HalLinkSource|null|undefined;
@@ -40,33 +40,33 @@ interface IOPFormModel {
}
interface IOPFieldSchema {
- type: OPFieldType;
- writable: boolean;
- allowedValues?: any;
- required?: boolean;
- hasDefault: boolean;
- name?: string;
- minLength?: number,
- maxLength?: number,
- attributeGroup?: string;
- location?: '_meta'|'_links'|undefined;
- options: {
- [key: string]: any;
+ type:OPFieldType;
+ writable:boolean;
+ allowedValues?:any;
+ required?:boolean;
+ hasDefault:boolean;
+ name?:string;
+ minLength?:number,
+ maxLength?:number,
+ attributeGroup?:string;
+ location?:'_meta'|'_links'|undefined;
+ options:{
+ [key:string]:any;
};
- _embedded?: {
- allowedValues?: IOPApiCall | IOPAllowedValue[];
+ _embedded?:{
+ allowedValues?:IOPApiCall | IOPAllowedValue[];
};
- _links?: {
- allowedValues?: IOPApiCall;
+ _links?:{
+ allowedValues?:IOPApiCall;
};
}
interface IOPFieldSchemaWithKey extends IOPFieldSchema {
- key: string;
+ key:string;
}
interface IOPFieldModel extends Partial<HalSource>{
- name?: string;
+ name?:string;
}
type HalSource = {
@@ -75,13 +75,13 @@ type HalSource = {
};
interface IOPApiCall {
- href: string;
- method?: string;
+ href:string;
+ method?:string;
}
interface IOPApiOption {
- href: string;
- title?: string;
+ href:string;
+ title?:string;
}
interface IOPAttributeGroup {
@@ -90,17 +90,17 @@ interface IOPAttributeGroup {
| "WorkPackageFormChildrenQueryGroup"
| "WorkPackageFormRelationQueryGroup"
| unknown;
- name: string;
- attributes: string[];
+ name:string;
+ attributes:string[];
}
interface IOPAllowedValue {
- id: string;
- name: string;
- [key: string]: unknown;
- _links: {
- self: HalSource | IOPApiOption;
- [key: string]: HalSource;
+ id:string;
+ name:string;
+ [key:string]:unknown;
+ _links:{
+ self:HalSource | IOPApiOption;
+ [key:string]:HalSource;
};
}
@@ -112,7 +112,7 @@ interface IOPFormError {
errorIdentifier:string;
message:string;
_type:string;
- _embedded: IOPFormErrorDetails;
+ _embedded:IOPFormErrorDetails;
}
interface IFormattedValidationError {
@@ -121,21 +121,21 @@ interface IFormattedValidationError {
}
interface IOPFormErrorResponse extends IOPFormError {
- _embedded: IOPFormErrorDetails | IOPFormErrors;
+ _embedded:IOPFormErrorDetails | IOPFormErrors;
}
interface IOPFormErrorDetails {
- details: {
- attribute: string;
+ details:{
+ attribute:string;
}
}
interface IOPFormErrors {
- errors: IOPFormError[];
+ errors:IOPFormError[];
}
interface IOPValidationErrors {
- [key: string]: IOPFormError;
+ [key:string]:IOPFormError;
}
diff --git a/frontend/src/app/modules/common/ckeditor/op-ckeditor.component.ts b/frontend/src/app/modules/common/ckeditor/op-ckeditor.component.ts
index 358a4d8f5c9..1d7854881e0 100644
--- a/frontend/src/app/modules/common/ckeditor/op-ckeditor.component.ts
+++ b/frontend/src/app/modules/common/ckeditor/op-ckeditor.component.ts
@@ -48,7 +48,14 @@ const manualModeLocalStorageKey = 'op-ckeditor-uses-manual-mode';
export class OpCkeditorComponent implements OnInit {
@Input() ckEditorType:'full'|'constrained' = 'full';
@Input() context:ICKEditorContext;
- @Input('content') _content:string;
+ @Input()
+ public set content(newVal:string) {
+ this._content = newVal;
+
+ if (this.initialized) {
+ this.ckEditorInstance!.setData(newVal);
+ }
+ }
// Output notification once ready
@Output() onInitialized = new EventEmitter<ICKEditorInstance>();
@@ -68,6 +75,7 @@ export class OpCkeditorComponent implements OnInit {
public error:string|null = null;
public allowManualMode = false;
public manualMode = false;
+ private _content:string;
public text = {
errorTitle: this.I18n.t('js.editor.error_initialization_failed')
@@ -138,15 +146,6 @@ export class OpCkeditorComponent implements OnInit {
});
}
- public set content(newVal:string) {
- if (!this.initialized) {
- throw "Tried to access CKEditor instance before initialization.";
- }
-
- this._content = newVal;
- this.ckEditorInstance!.setData(newVal);
- }
-
/**
* Return the current content. This may be outdated a tiny bit.
*/
diff --git a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-field-wrapper/dynamic-field-wrapper.component.html b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-field-wrapper/dynamic-field-wrapper.component.html
index 22be0abdc51..145e8d7c7c5 100644
--- a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-field-wrapper/dynamic-field-wrapper.component.html
+++ b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-field-wrapper/dynamic-field-wrapper.component.html
@@ -1,13 +1,16 @@
<op-form-field
- [label]="to?.label"
- [noWrapLabel]="to?.noWrapLabel"
- [required]="to?.required"
- [helpTextAttribute]="to?.property"
- [helpTextAttributeScope]="to?.helpTextAttributeScope"
- [attr.data-qa-field-name]="to?.property"
- [ngClass]="{ 'op-form-field_checkbox': field.type === 'booleanInput' }"
+ [control]="field?.formControl"
+ [label]="to?.label"
+ [hidden]="field?.hide"
+ [noWrapLabel]="to?.noWrapLabel"
+ [required]="to?.required"
+ [helpTextAttribute]="to?.property"
+ [helpTextAttributeScope]="to?.helpTextAttributeScope || dynamicFormComponent?.helpTextAttributeScope"
+ [showValidationErrorOn]="to?.showValidationErrorOn || dynamicFormComponent?.showValidationErrorsOn"
+ [attr.data-qa-field-name]="to?.property"
>
<ng-container #fieldComponent slot="input"></ng-container>
+
<formly-validation-message
class="op-form-field--error"
[field]="field"
diff --git a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-field-wrapper/dynamic-field-wrapper.component.ts b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-field-wrapper/dynamic-field-wrapper.component.ts
index f9d4c1840ad..d5bac31d778 100644
--- a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-field-wrapper/dynamic-field-wrapper.component.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-field-wrapper/dynamic-field-wrapper.component.ts
@@ -1,5 +1,6 @@
-import { Component, ChangeDetectionStrategy } from '@angular/core';
+import { Component, ChangeDetectionStrategy, Optional } from '@angular/core';
import { FieldWrapper } from "@ngx-formly/core";
+import { DynamicFormComponent } from "core-app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component";
@Component({
selector: 'op-dynamic-field-wrapper',
@@ -8,4 +9,9 @@ import { FieldWrapper } from "@ngx-formly/core";
changeDetection: ChangeDetectionStrategy.OnPush
})
export class DynamicFieldWrapperComponent extends FieldWrapper {
+ constructor(
+ @Optional() public dynamicFormComponent:DynamicFormComponent,
+ ) {
+ super();
+ }
}
diff --git a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component.spec.ts b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component.spec.ts
index a91085db18a..5fc2e336928 100644
--- a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component.spec.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component.spec.ts
@@ -1,7 +1,7 @@
import { NgSelectModule } from "@ng-select/ng-select";
import { NgOptionHighlightModule } from "@ng-select/ng-option-highlight";
import { Component, forwardRef, ViewChild } from "@angular/core";
-import { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';
+import { ComponentFixture, fakeAsync, flush, TestBed } from '@angular/core/testing';
import { By } from "@angular/platform-browser";
import { defer, of } from "rxjs";
import { FormControl, FormGroup, NG_VALUE_ACCESSOR, ReactiveFormsModule } from "@angular/forms";
@@ -23,6 +23,7 @@ import { FormattableTextareaInputComponent } from "core-app/modules/common/dynam
import { DynamicFieldGroupWrapperComponent } from "core-app/modules/common/dynamic-forms/components/dynamic-field-group-wrapper/dynamic-field-group-wrapper.component";
import { OpFormFieldComponent } from "core-app/modules/common/forms/form-field/form-field.component";
import { HttpClientTestingModule } from "@angular/common/http/testing";
+import { DynamicFieldWrapperComponent } from "core-app/modules/common/dynamic-forms/components/dynamic-field-wrapper/dynamic-field-wrapper.component";
@Component({
template: `
@@ -294,6 +295,10 @@ describe('DynamicFormComponent', () => {
name: "op-dynamic-field-group-wrapper",
component: DynamicFieldGroupWrapperComponent,
},
+ {
+ name: 'op-dynamic-field-wrapper',
+ component: DynamicFieldWrapperComponent,
+ },
]
}),
NgSelectModule,
@@ -307,6 +312,8 @@ describe('DynamicFormComponent', () => {
SelectInputComponent,
BooleanInputComponent,
DynamicFormsTestingComponent,
+ DynamicFieldGroupWrapperComponent,
+ DynamicFieldWrapperComponent,
// Skip adding DateInputComponent and FormattableTextareaInputComponent
// to keep it simple (inheritance test issues).
],
@@ -353,7 +360,7 @@ describe('DynamicFormComponent', () => {
dynamicFormService.getSettingsFromBackend$.and.returnValue(defer(() => Promise.resolve(dynamicFormSettings)));
component.resourcePath = '/api/v3/projects/1234/form';
- component.ngOnChanges({});
+ component.ngOnChanges({ resourcePath: { currentValue: '/api/v3/projects/1234/form' }} as any);
expect(dynamicFormService.getSettingsFromBackend$).toHaveBeenCalled();
@@ -410,7 +417,7 @@ describe('DynamicFormComponent', () => {
component.showNotifications = false;
component.resourcePath = '/api/v3/projects/1234/form';
- component.ngOnChanges({});
+ component.ngOnChanges({ resourcePath: { currentValue: '/api/v3/projects/1234/form' }} as any);
flush();
fixture.detectChanges();
submitButton = fixture.debugElement.query(By.css('button[type=submit]'));
@@ -469,11 +476,8 @@ describe('DynamicFormComponent', () => {
dynamicFormService.getSettingsFromBackend$.and.returnValue(defer(() => Promise.resolve(dynamicFormSettingsForSubmit)));
dynamicFormService.submit$.and.returnValue(defer(() => Promise.resolve('ok')));
- // Should not show notifications when showNotifications === false
- component.showNotifications = false;
-
component.resourcePath = '/api/v3/projects/1234/form';
- component.ngOnChanges({});
+ component.ngOnChanges({ resourcePath: { currentValue: '/api/v3/projects/1234/form' }} as any);
flush();
fixture.detectChanges();
const submitButton = fixture.debugElement.query(By.css('button[type=submit]'));
diff --git a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component.ts b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component.ts
index df522f3b5bc..cad72d64470 100644
--- a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component.ts
@@ -10,7 +10,7 @@ import {
} from "@angular/core";
import { FormlyForm } from "@ngx-formly/core";
import { DynamicFormService } from "../../services/dynamic-form/dynamic-form.service";
-import { IOPDynamicFormSettings, IOPFormlyFieldSettings } from "../../typings";
+import { IDynamicFieldGroupConfig, IOPDynamicFormSettings, IOPFormlyFieldSettings } from "../../typings";
import { I18nService } from "core-app/modules/common/i18n/i18n.service";
import { PathHelperService } from "core-app/modules/common/path-helper/path-helper.service";
import { catchError, finalize } from "rxjs/operators";
@@ -20,50 +20,99 @@ import { DynamicFieldsService } from "core-app/modules/common/dynamic-forms/serv
import { FormGroup } from "@angular/forms";
import { UntilDestroyedMixin } from "core-app/helpers/angular/until-destroyed.mixin";
import { FormsService } from "core-app/core/services/forms/forms.service";
+import { HttpErrorResponse } from "@angular/common/http";
-/*
+/**
* SETTINGS:
* The DynamicFormComponent can get its settings (payload and fields) in two ways:
*
* - @Input settings:
* Passing down an object that mimics a backend form configuration (IOPFormSettings),
-* with and easier format (not _embedded).
+* with and easier format (not _embedded) through the 'settings' @Input.
*
+* ```
* <op-dynamic-form [settings]="formSettings">
* </op-dynamic-form>
+* ```
*
* - Backend settings:
* In order to fetch its settings from the backend, the DynamicFormComponent will
-* always need the 'resourcePath' @Input and, optionally, the 'resourceId' @Input if
-* we are editing a resource.
+* always need a backend endpoint to target. It can be provided in two ways:
+* - Through the 'resourcePath' @Input and, optionally, the 'resourceId' @Input if
+* we are editing an existing form.
*
-* <op-dynamic-form [resourcePath]="resourcePath">
-* </op-dynamic-form>
+* ```
+* <op-dynamic-form [resourcePath]="resourcePath">
+* </op-dynamic-form>
+* ```
+*
+* - Through the the 'formUrl' @Input. In this case we'll need to also provide the
+* formHttpMethod @Input if it is not POST.
+*
+* ```
+* <op-dynamic-form [formUrl]="formUrl"
+* [formHttpMethod]="formHttpMethod">
+* </op-dynamic-form>
+* ```
*
* USE CASES:
* The DynamicFormComponent can be used in two ways:
*
* - Standalone Form:
-* In order to work as an standalone form, handling the submit operation by
-* showing a submit button, the DynamicFormComponent will always need the
-* 'resourcePath' @Input and, optionally, the 'resourceId' @Input if we are
-* editing a single resource.
+* In order to work as an standalone form, handling the submit operation,
+* the DynamicFormComponent will need a backend endpoint to target as explained above.
+ *
+* ```
+* <op-dynamic-form [resourcePath]="resourcePath">
+* </op-dynamic-form>
+* ```
*
-* <op-dynamic-form [resourcePath]="projectsPath">
-* </op-dynamic-form>
+* - FormGroup:
+* In order to use the DynamicFormComponent as a formGroup, it will need a
+* FormGroup to be passed through the dynamicFormGroup @Input.
*
-* - FormControl:
-* The DynamicFormComponent can be used inside a FormGroup as a FormControl.
+* ```
+* <op-dynamic-form [dynamicFormGroup]="dynamicFormGroup">
+* </op-dynamic-form>`
+* ```
*
-* <op-dynamic-form formControlName="workpackage"
-* [settings]="formSettings">
-* </op-dynamic-form>
+* FORM SETTINGS CUSTOMIZATIONS:
+* The form settings can be customized in different ways:
+*
+* - initialPayload @Input:
+* Allows to provide and initial payload to the form settings request. Checkout
+* the [forms documentation](https://docs.openproject.org/api/forms/).
*
-* When used as a FormControl (formControlName), the DynamicFormComponent will set
-* the entire form value as the value of the FormControl. Using it as a FormGroup
-* (formGroupName) would require to pass down the configuration of the form in order
-* to use the DynamicFormComponent, which would make no sense because what this
-* component does is to generate a form automatically from a configuration object.
+* - model @Input:
+* Allows to change model of the form.
+*
+* - fieldsSettingsPipe:
+* Allows to modify the dynamicFormFields settings before the form is rendered.
+ *
+* ```
+* <op-dynamic-form [formUrl]="formUrl"
+* [formHttpMethod]="formHttpMethod"
+* [initialPayload]="initialPayload">
+* </op-dynamic-form>
+* ```
+*
+* - fieldGroups:
+* Allows to create field groups programmatically. For example, the following group would
+* create an 'Advanced settings' field group with all the fields that are not 'name'
+* or 'parent' overriding the default collapsibleFieldGroupsCollapsed (showing them
+* uncollapsed).
+*
+* ```
+* const fieldGroups = [{
+* name: 'Advanced settings',
+* fieldsFilter: (field) => !['name', 'parent'].includes(field.templateOptions?.property!),
+ * settings: {
+ * templateOptions: {
+ * collapsibleFieldGroupsCollapsed: false
+ * }
+ * }
+* }];
+* ```
*/
@Component({
@@ -76,63 +125,60 @@ import { FormsService } from "core-app/core/services/forms/forms.service";
],
})
export class DynamicFormComponent extends UntilDestroyedMixin implements OnChanges {
- // Backend form URL (e.g. https://community.openproject.org/api/v3/projects/dev-large/form)
- @Input() formUrl:string;
- // When using the formUrl @Input(), set the http method to use if it is not 'POST'
- @Input() formHttpMethod:'post'|'patch' = 'post';
- // Part of the URL that belongs to the resource type (e.g. '/projects' in the previous example)
- // Use this option when you don't have a form URL, the DynamicForm will build it from the resourcePath
- // for you (⌐■_■).
- @Input() resourcePath:string;
- // Pass the resourceId in case you are editing an existing resource and you don't have the Form URL.
- @Input() resourceId:string;
- @Input() settings:IOPFormSettings;
- // Chance to modify the dynamicFormFields settings before the form is rendered
- @Input() fieldsSettingsPipe:(dynamicFieldsSettings:IOPFormlyFieldSettings[]) => IOPFormlyFieldSettings[];
- @Input() showNotifications = true;
- @Input() showValidationErrorsOn:'change'|'blur'|'submit'|'never' = 'submit';
- @Input() handleSubmit = true;
- @Input() helpTextAttributeScope:string|undefined;
- @Input() dynamicFormGroup:FormGroup;
-
+ /** Backend form URL (e.g. https://community.openproject.org/api/v3/projects/dev-large/form) */
+ @Input() formUrl?:string;
+ /** When using the formUrl @Input(), set the http method to use if it is not 'POST' */
+ @Input() formHttpMethod?:'post'|'patch' = 'post';
+ /** Part of the URL that belongs to the resource type (e.g. '/projects' in the previous example)
+ * Use this option when you don't have a form URL, the DynamicForm will build it from the resourcePath
+ * for you (⌐■_■).
+ */
+ @Input() resourcePath?:string;
+ /** Pass the resourceId in case you are editing an existing resource and you don't have the Form URL. */
+ @Input() resourceId?:string;
+ @Input() settings?:IOPFormSettings;
+ @Input() dynamicFormGroup?:FormGroup;
+ /** Initial payload to POST to the form */
+ @Input() initialPayload:Object = {};
@Input() set model(payload:IOPFormModel) {
- if (!this.innerModel && !payload) {
- return;
- }
+ if (!this.innerModel && !payload) { return; }
const formattedModel = this._dynamicFieldsService.getFormattedFieldsModel(payload);
- this.innerModel = formattedModel;
+
+ this.form.patchValue(formattedModel);
}
+ /** Chance to modify the dynamicFormFields settings before the form is rendered */
+ @Input() fieldsSettingsPipe?:(dynamicFieldsSettings:IOPFormlyFieldSettings[]) => IOPFormlyFieldSettings[];
+ /** Create fieldGroups programmatically */
+ @Input() fieldGroups?:IDynamicFieldGroupConfig[];
+ @Input() showNotifications = true;
+ @Input() showValidationErrorsOn:'change'|'blur'|'submit'|'never' = 'submit';
+ @Input() handleSubmit = true;
+ @Input() helpTextAttributeScope?:string;
- /** Initial payload to POST to the form */
- @Input() initialPayload:Object = {};
@Output() modelChange = new EventEmitter<IOPFormModel>();
@Output() submitted = new EventEmitter<HalSource>();
@Output() errored = new EventEmitter<IOPFormErrorResponse>();
+ form:FormGroup;
fields:IOPFormlyFieldSettings[];
formEndpoint?:string;
inFlight:boolean;
text = {
save: this._I18n.t('js.button_save'),
- validation_error_message: this._I18n.t('js.forms.validation_error_message'),
load_error_message: this._I18n.t('js.forms.load_error_message'),
successful_update: this._I18n.t('js.notice_successful_update'),
successful_create: this._I18n.t('js.notice_successful_create'),
+ job_started: this._I18n.t('js.notice_job_started'),
};
- noSettingsSourceErrorMessage = `DynamicFormComponent needs a settings or resourcePath @Input
+ noSettingsSourceErrorMessage = `DynamicFormComponent needs a settings, formUrl or resourcePath @Input
in order to fetch its setting. Please provide one.`;
- noPathToSubmitToError = `DynamicForm needs a resourcePath input in order to be submitted
+ noPathToSubmitToError = `DynamicForm needs a resourcePath or formUrl @Input in order to be submitted
and validated. Please provide one.`;
innerModel:IOPFormModel;
- form:FormGroup;
get model() {
- return this.form.value;
- }
-
- get isStandaloneForm():boolean {
- return !this.settings;
+ return this.form.getRawValue();
}
@ViewChild(FormlyForm)
@@ -157,13 +203,25 @@ export class DynamicFormComponent extends UntilDestroyedMixin implements OnChang
}
ngOnChanges(changes:SimpleChanges) {
- this._initializeDynamicForm(
- changes?.settings?.currentValue,
- this.resourcePath,
- this.resourceId,
- this.formUrl,
- this.innerModel || this.initialPayload,
- );
+ if (
+ changes.settings ||
+ changes.resourcePath ||
+ changes.resourceId ||
+ changes.formUrl ||
+ changes.formHttpMethod ||
+ changes.dynamicFormGroup ||
+ changes.initialPayload ||
+ changes.fieldsSettingsPipe ||
+ changes.fieldGroups
+ ) {
+ this.initializeDynamicForm(
+ this.settings,
+ this.resourcePath,
+ this.resourceId,
+ this.formUrl,
+ this.initialPayload,
+ );
+ }
}
onModelChange(changes:any) {
@@ -186,22 +244,17 @@ export class DynamicFormComponent extends UntilDestroyedMixin implements OnChang
finalize(() => this.inFlight = false),
)
.subscribe(
- (formResource:HalSource) => {
- this.submitted.emit(formResource);
- this.showNotifications && this.showSuccessNotification();
+ (formResponse:HalSource|any) => {
+ this.submitted.emit(formResponse);
+ this.showNotifications && this.showSuccessNotification(formResponse);
},
- (error:IOPFormErrorResponse) => {
- this.errored.emit(error);
- this.showNotifications && this._notificationsService.addError(this.text.validation_error_message);
+ (error:HttpErrorResponse) => {
+ this.errored.emit(error?.error || error);
+ this.showNotifications && this._notificationsService.addError(error?.error?.message || error?.message);
},
);
}
- private showSuccessNotification():void {
- const submit_message = this.resourceId ? this.text.successful_update : this.text.successful_create;
- this._notificationsService.addSuccess(submit_message);
- }
-
validateForm() {
if (!this.formEndpoint) {
throw new Error(this.noPathToSubmitToError);
@@ -210,31 +263,31 @@ export class DynamicFormComponent extends UntilDestroyedMixin implements OnChang
return this._formsService.validateForm$(this.form, this.formEndpoint);
}
- private _initializeDynamicForm(
+ private initializeDynamicForm(
settings?:IOPFormSettings,
resourcePath?:string,
resourceId?:string,
formUrl?:string,
payload?:Object,
) {
- const newFormEndPoint = this._getFormEndPoint(formUrl, resourcePath);
- if (!newFormEndPoint) {
+ const formEndPoint = this.getFormEndPoint(formUrl, resourcePath);
+ if (!formEndPoint) {
throw new Error(this.noSettingsSourceErrorMessage);
}
- const isNewEndpoint = newFormEndPoint !== this.formEndpoint;
+ const isNewEndpoint = formEndPoint !== this.formEndpoint;
if (isNewEndpoint) {
- this.formEndpoint = newFormEndPoint;
+ this.formEndpoint = formEndPoint;
}
if (settings) {
- this._setupDynamicFormFromSettings();
+ this.setupDynamicFormFromSettings();
} else {
- this._setupDynamicFormFromBackend(this.formEndpoint, resourceId, payload);
+ this.setupDynamicFormFromBackend(this.formEndpoint, resourceId, payload);
}
}
- private _getFormEndPoint(formUrl?:string, resourcePath?:string):string|undefined {
+ private getFormEndPoint(formUrl?:string, resourcePath?:string):string|undefined {
if (formUrl) {
return formUrl.endsWith(`/form`) ?
formUrl.replace(`/form`, ``) :
@@ -248,7 +301,7 @@ export class DynamicFormComponent extends UntilDestroyedMixin implements OnChang
return;
}
- private _setupDynamicFormFromBackend(formEndpoint?:string, resourceId?:string, payload?:Object) {
+ private setupDynamicFormFromBackend(formEndpoint?:string, resourceId?:string, payload?:Object) {
this._dynamicFormService
.getSettingsFromBackend$(formEndpoint, resourceId, payload)
.pipe(
@@ -257,33 +310,48 @@ export class DynamicFormComponent extends UntilDestroyedMixin implements OnChang
throw error;
}),
)
- .subscribe(dynamicFormSettings => this._setupDynamicForm(dynamicFormSettings));
+ .subscribe(dynamicFormSettings => this.setupDynamicForm(dynamicFormSettings));
}
- private _setupDynamicFormFromSettings() {
+ private setupDynamicFormFromSettings() {
const formattedSettings:IOPFormSettingsResource = {
_embedded: {
- payload: this.settings.payload,
- schema: this.settings.schema,
+ payload: this.settings!.payload,
+ schema: this.settings!.schema,
},
};
const dynamicFormSettings = this._dynamicFormService.getSettings(formattedSettings);
- this._setupDynamicForm(dynamicFormSettings);
+ this.setupDynamicForm(dynamicFormSettings);
}
- private _setupDynamicForm({ fields, model, form }:IOPDynamicFormSettings) {
- const scopedFields = fields.map(field => ({
- ...field,
- templateOptions: {
- ...field.templateOptions,
- helpTextAttributeScope: this.helpTextAttributeScope,
- },
- }));
- this.fields = this.fieldsSettingsPipe ? this.fieldsSettingsPipe(scopedFields) : scopedFields;
+ private setupDynamicForm({ fields, model, form }:IOPDynamicFormSettings) {
+ if (this.fieldsSettingsPipe) {
+ fields = this.fieldsSettingsPipe(fields);
+ }
+
+ if (this.fieldGroups) {
+ fields = this._dynamicFieldsService.getFormlyFormWithFieldGroups(this.fieldGroups, fields);
+ }
+
+ this.fields = fields;
this.innerModel = model;
this.form = this.dynamicFormGroup || form;
this._changeDetectorRef.detectChanges();
}
+
+ private showSuccessNotification(formResponse:HalSource|any):void {
+ let submit_message;
+
+ if (formResponse?.jobId) {
+ const title = formResponse?.payload?.title;
+
+ submit_message = `${title || ''} ${this.text.job_started}`;
+ } else {
+ submit_message = this.resourceId ? this.text.successful_update : this.text.successful_create;
+ }
+
+ this._notificationsService.addSuccess(submit_message);
+ }
}
diff --git a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/date-input/components/date-picker-adapter/date-picker-adapter.component.ts b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/date-input/components/date-picker-adapter/date-picker-adapter.component.ts
index f649edb4038..ec29f879daa 100644
--- a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/date-input/components/date-picker-adapter/date-picker-adapter.component.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/date-input/components/date-picker-adapter/date-picker-adapter.component.ts
@@ -21,8 +21,8 @@ export class DatePickerAdapterComponent extends OpDatePickerComponent implements
constructor(
timezoneService:TimezoneService,
- private _ngZone: NgZone,
- private _changeDetectorRef:ChangeDetectorRef,
+ private ngZone: NgZone,
+ private changeDetectorRef:ChangeDetectorRef,
) {
super(timezoneService);
}
@@ -44,10 +44,10 @@ export class DatePickerAdapterComponent extends OpDatePickerComponent implements
}
ngAfterViewInit():void {
- this._ngZone.runOutsideAngular(() => {
+ this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
this.initializeDatepicker();
- this._changeDetectorRef.detectChanges();
+ this.changeDetectorRef.detectChanges();
});
});
}
diff --git a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/formattable-textarea-input/components/formattable-control/formattable-control.component.ts b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/formattable-textarea-input/components/formattable-control/formattable-control.component.ts
index 65a2e4e9f4e..32cc06bf5b2 100644
--- a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/formattable-textarea-input/components/formattable-control/formattable-control.component.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/formattable-textarea-input/components/formattable-control/formattable-control.component.ts
@@ -73,14 +73,10 @@ export class FormattableControlComponent implements OnInit {
}
onContentChange(value:string) {
- this.editor
- .getTransformedContent()
- .then((val) => {
- const valueToEmit = {raw: val};
+ const valueToEmit = {raw: value};
- this.onTouch();
- this.onChange(valueToEmit);
- });
+ this.onTouch();
+ this.onChange(valueToEmit);
}
onCkeditorSetup(editor:ICKEditorInstance) {
diff --git a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/formattable-textarea-input/formattable-textarea-input.component.spec.ts b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/formattable-textarea-input/formattable-textarea-input.component.spec.ts
index e0c3a6a4e17..3d703d04240 100644
--- a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/formattable-textarea-input/formattable-textarea-input.component.spec.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/formattable-textarea-input/formattable-textarea-input.component.spec.ts
@@ -36,13 +36,13 @@ describe('FormattableTextareaInputComponent', () => {
};
const fixture = createDynamicInputFixture(fieldsConfig, formModel);
const dynamicInput = fixture.debugElement.query(By.css('.document-editor__editable-container')).nativeElement;
- const dynamicControl = fixture.componentInstance.dynamicControl.field.formControl;
+ const dynamicForm = fixture.componentInstance.dynamicForm.field.formControl;
const dynamicDebugElement = fixture.debugElement.query(By.css('op-formattable-control'));
const dynamicElement = dynamicDebugElement.nativeElement;
// Test ControlValueAccessor
// Write Value
- expect(dynamicControl.value.testControl).toEqual(testModel.initialValue);
+ expect(dynamicForm.value.testControl).toEqual(testModel.initialValue);
expect(dynamicElement.classList.contains('ng-untouched')).toBeTrue();
expect(dynamicElement.classList.contains('ng-valid')).toBeTrue();
expect(dynamicElement.classList.contains('ng-pristine')).toBeTrue();
diff --git a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/select-input/select-input.component.spec.ts b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/select-input/select-input.component.spec.ts
index 99a1b10dc98..2d9359d602e 100644
--- a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/select-input/select-input.component.spec.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/select-input/select-input.component.spec.ts
@@ -41,14 +41,14 @@ describe('SelectInputComponent', () => {
changedValue: selectOptions[1],
};
const fixture = createDynamicInputFixture(fieldsConfig, formModel);
- const dynamicControl = fixture.componentInstance.dynamicControl.field.formControl;
+ const dynamicForm = fixture.componentInstance.dynamicForm.field.formControl;
const dynamicInput = fixture.debugElement.query(By.css('op-select-input input')).nativeElement;
const dynamicDebugElement = fixture.debugElement.query(By.css('ng-select'));
const dynamicElement = dynamicDebugElement.nativeElement;
// Test ControlValueAccessor
// Write Value
- expect(dynamicControl.value.testControl).toBe(testModel.initialValue);
+ expect(dynamicForm.value.testControl).toBe(testModel.initialValue);
expect(dynamicElement.classList.contains('ng-untouched')).toBeTrue();
expect(dynamicElement.classList.contains('ng-valid')).toBeTrue();
expect(dynamicElement.classList.contains('ng-pristine')).toBeTrue();
@@ -74,7 +74,7 @@ describe('SelectInputComponent', () => {
fixture.detectChanges();
flush();
- expect(dynamicControl.value.testControl).toBe(testModel.changedValue);
+ expect(dynamicForm.value.testControl).toBe(testModel.changedValue);
expect(dynamicElement.classList.contains('ng-dirty')).toBeTrue();
// Blur
@@ -83,7 +83,7 @@ describe('SelectInputComponent', () => {
expect(dynamicElement.classList.contains('ng-touched')).toBeTrue();
// Disabled
- dynamicControl.disable();
+ dynamicForm.disable();
fixture.detectChanges();
expect(dynamicInput.disabled).toBeTrue();
}));
diff --git a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/text-input/text-input.component.spec.ts b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/text-input/text-input.component.spec.ts
index 807c1a1d65b..d45e03e6399 100644
--- a/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/text-input/text-input.component.spec.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/components/dynamic-inputs/text-input/text-input.component.spec.ts
@@ -4,7 +4,7 @@ import {
testDynamicInputControValueAccessor,
} from "core-app/modules/common/dynamic-forms/spec/helpers";
-describe('TextComponent', () => {
+describe('TextInputComponent', () => {
it('should load the field', fakeAsync(() => {
const fieldsConfig = [
{
diff --git a/frontend/src/app/modules/common/dynamic-forms/services/dynamic-fields/dynamic-fields.service.spec.ts b/frontend/src/app/modules/common/dynamic-forms/services/dynamic-fields/dynamic-fields.service.spec.ts
index ab61f9b1734..11bb7d88258 100644
--- a/frontend/src/app/modules/common/dynamic-forms/services/dynamic-fields/dynamic-fields.service.spec.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/services/dynamic-fields/dynamic-fields.service.spec.ts
@@ -3,6 +3,7 @@ import { HttpClientTestingModule, HttpTestingController } from "@angular/common/
import { HttpClient } from "@angular/common/http";
import { DynamicFieldsService } from "core-app/modules/common/dynamic-forms/services/dynamic-fields/dynamic-fields.service";
import { isObservable } from "rxjs";
+import { IOPFormlyFieldSettings } from "core-app/modules/common/dynamic-forms/typings";
describe('DynamicFieldsService', () => {
let httpClient: HttpClient;
@@ -73,7 +74,7 @@ describe('DynamicFieldsService', () => {
};
// @ts-ignore
- const fieldsSchemas = service._getFieldsSchemasWithKey(formSchema, formPayload);
+ const fieldsSchemas = service.getFieldsSchemasWithKey(formSchema, formPayload);
expect(fieldsSchemas.length).toBe(2, 'should return only writable field schemas');
expect(fieldsSchemas[0].key).toBe('name', 'should place the correct key on primitives');
@@ -198,7 +199,7 @@ describe('DynamicFieldsService', () => {
const formlyConfig = service.getConfig(formSchema, formPayload);
const formlyFields = formlyConfig.reduce((result, formlyField) => {
return formlyField.fieldGroup ? [...result, ...formlyField.fieldGroup] : [...result, formlyField];
- }, []);
+ }, [] as IOPFormlyFieldSettings[]);
const formGroup = formlyConfig[1];
expect(formlyFields[1].templateOptions!.label).toBe('Name', 'should set the correct label');
diff --git a/frontend/src/app/modules/common/dynamic-forms/services/dynamic-fields/dynamic-fields.service.ts b/frontend/src/app/modules/common/dynamic-forms/services/dynamic-fields/dynamic-fields.service.ts
index 53ae9d1a459..7a08a0c812f 100644
--- a/frontend/src/app/modules/common/dynamic-forms/services/dynamic-fields/dynamic-fields.service.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/services/dynamic-fields/dynamic-fields.service.ts
@@ -1,5 +1,6 @@
import { Injectable } from '@angular/core';
import {
+ IDynamicFieldGroupConfig,
IOPDynamicInputTypeSettings,
IOPFormlyFieldSettings,
} from "../../typings";
@@ -116,12 +117,15 @@ export class DynamicFieldsService {
}
getConfig(formSchema:IOPFormSchema, formPayload:IOPFormModel):IOPFormlyFieldSettings[] {
- const formFieldGroups = formSchema._attributeGroups;
- const fieldSchemas = this._getFieldsSchemasWithKey(formSchema);
+ const formFieldGroups = formSchema._attributeGroups?.map(fieldGroup => ({
+ name: fieldGroup.name,
+ fieldsFilter: (field:IOPFormlyFieldSettings) => fieldGroup.attributes?.includes(field.templateOptions?.property!),
+ }));
+ const fieldSchemas = this.getFieldsSchemasWithKey(formSchema);
const formlyFields = fieldSchemas
- .map(fieldSchema => this._getFormlyFieldConfig(fieldSchema, formPayload))
+ .map(fieldSchema => this.getFormlyFieldConfig(fieldSchema, formPayload))
.filter(f => f !== null) as IOPFormlyFieldSettings[];
- const formlyFormWithFieldGroups = this._getFormlyFormWithFieldGroups(formFieldGroups, formlyFields);
+ const formlyFormWithFieldGroups = this.getFormlyFormWithFieldGroups(formFieldGroups, formlyFields);
return formlyFormWithFieldGroups;
}
@@ -136,13 +140,20 @@ export class DynamicFieldsService {
const model = {
...otherElementsModel,
_meta: metaModel,
- _links: this._getFormattedResourcesModel(resourcesModel),
+ _links: this.getFormattedResourcesModel(resourcesModel),
};
return model;
}
- private _getFieldsSchemasWithKey(formSchema:IOPFormSchema):IOPFieldSchemaWithKey[] {
+ getFormlyFormWithFieldGroups(fieldGroups:IDynamicFieldGroupConfig[] = [], formFields:IOPFormlyFieldSettings[] = []):IOPFormlyFieldSettings[] {
+ const fomFieldsWithoutGroup = formFields.filter(formField => fieldGroups.every(fieldGroup => !fieldGroup.fieldsFilter || !fieldGroup.fieldsFilter(formField)));
+ const formFieldGroups = this.getDynamicFormFieldGroups(fieldGroups, formFields);
+
+ return [...fomFieldsWithoutGroup, ...formFieldGroups];
+ }
+
+ private getFieldsSchemasWithKey(formSchema:IOPFormSchema):IOPFieldSchemaWithKey[] {
return Object.keys(formSchema)
.map(fieldSchemaKey => {
const fieldSchema = {
@@ -152,7 +163,7 @@ export class DynamicFieldsService {
return fieldSchema;
})
- .filter(fieldSchema => this._isFieldSchema(fieldSchema) && fieldSchema.writable);
+ .filter(fieldSchema => this.isFieldSchema(fieldSchema) && fieldSchema.writable);
}
private getAttributeKey(fieldSchema:IOPFieldSchema, key:string):string {
@@ -165,11 +176,11 @@ export class DynamicFieldsService {
}
}
- private _isFieldSchema(schemaValue:IOPFieldSchemaWithKey|any):boolean {
+ private isFieldSchema(schemaValue:IOPFieldSchemaWithKey|any):boolean {
return !!schemaValue?.type;
}
- private _getFormattedResourcesModel(resourcesModel:IOPFormModel['_links'] = {}):IOPFormModel['_links'] {
+ private getFormattedResourcesModel(resourcesModel:IOPFormModel['_links'] = {}):IOPFormModel['_links'] {
return Object.keys(resourcesModel).reduce((result, resourceKey) => {
const resource = resourcesModel[resourceKey];
// ng-select needs a 'name' in order to show the label
@@ -190,14 +201,14 @@ export class DynamicFieldsService {
}, {});
}
- private _getFormlyFieldConfig(fieldSchema:IOPFieldSchemaWithKey, formPayload:IOPFormModel):IOPFormlyFieldSettings|null {
+ private getFormlyFieldConfig(fieldSchema:IOPFieldSchemaWithKey, formPayload:IOPFormModel):IOPFormlyFieldSettings|null {
const { key, name: label, required, hasDefault, minLength, maxLength } = fieldSchema;
- const fieldTypeConfigSearch = this._getFieldTypeConfig(fieldSchema);
+ const fieldTypeConfigSearch = this.getFieldTypeConfig(fieldSchema);
if (!fieldTypeConfigSearch) {
return null;
}
const { templateOptions, ...fieldTypeConfig } = fieldTypeConfigSearch;
- const fieldOptions = this._getFieldOptions(fieldSchema);
+ const fieldOptions = this.getFieldOptions(fieldSchema);
const property = this.getFieldProperty(key);
const payloadValue = property && formPayload[property];
const formlyFieldConfig = {
@@ -221,7 +232,7 @@ export class DynamicFieldsService {
return formlyFieldConfig;
}
- private _getFieldTypeConfig(field:IOPFieldSchemaWithKey):IOPFormlyFieldSettings|null {
+ private getFieldTypeConfig(field:IOPFieldSchemaWithKey):IOPFormlyFieldSettings|null {
const fieldType = field.type.replace('[]', '') as OPFieldType;
let inputType = this.inputsCatalogue.find(inputType => inputType.useForFields.includes(fieldType))!;
if (!inputType) {
@@ -256,7 +267,7 @@ export class DynamicFieldsService {
return { ...inputConfig, ...configCustomizations };
}
- private _getFieldOptions(field:IOPFieldSchemaWithKey) {
+ private getFieldOptions(field:IOPFieldSchemaWithKey) {
const allowedValues = field._embedded?.allowedValues || field._links?.allowedValues;
if (!allowedValues) {
@@ -265,7 +276,7 @@ export class DynamicFieldsService {
if (Array.isArray(allowedValues)) {
const options = allowedValues[0]?._links?.self?.title ?
- this._formatAllowedValues(allowedValues) :
+ this.formatAllowedValues(allowedValues) :
allowedValues;
return of(options);
@@ -274,7 +285,7 @@ export class DynamicFieldsService {
.get(allowedValues!.href!)
.pipe(
map((response:api.v3.Result) => response._embedded.elements),
- map(options => this._formatAllowedValues(options)),
+ map(options => this.formatAllowedValues(options)),
);
}
@@ -283,7 +294,7 @@ export class DynamicFieldsService {
// ng-select needs a 'name' in order to show the label
// We need to add it in case of the form payload (HalLinkSource)
- private _formatAllowedValues(options:IOPAllowedValue[]) {
+ private formatAllowedValues(options:IOPAllowedValue[]) {
return options.map((option:IOPFieldSchema['options']) => ({ ...option, name: option._links?.self?.title }));
}
@@ -292,60 +303,81 @@ export class DynamicFieldsService {
return key.split('.').pop();
}
- private _getFormlyFormWithFieldGroups(fieldGroups:IOPAttributeGroup[] = [], formFields:IOPFormlyFieldSettings[] = []):IOPFormlyFieldSettings[] {
- const fieldGroupKeys = fieldGroups.reduce((groupKeys, fieldGroup) => [...groupKeys, ...fieldGroup.attributes], []);
- const formFieldsWithoutGroup = formFields
- .filter(formField => {
- const formFieldKey = formField.key && this.getFieldProperty(formField.key);
-
- return formFieldKey ?
- !fieldGroupKeys.includes(formFieldKey) :
- true;
- });
-
- const formFieldGroups = fieldGroups.reduce((formWithFieldGroups:IOPFormlyFieldSettings[], fieldGroup) => {
- const newFormFieldGroup = {
- templateOptions: {
- label: fieldGroup.name,
- isFieldGroup: true,
- collapsibleFieldGroups: false,
- collapsibleFieldGroupsCollapsed: true,
- },
- fieldGroup: formFields.filter(formField => {
- const formFieldKey = formField.key && this.getFieldProperty(formField.key);
+ private getDynamicFormFieldGroups(fieldGroups:IDynamicFieldGroupConfig[] = [], formFields:IOPFormlyFieldSettings[] = []) {
+ return fieldGroups.reduce((formWithFieldGroups:IOPFormlyFieldSettings[], fieldGroup) => {
+ let newFormFieldGroup = this.getDefaultFieldGroupSettings(fieldGroup, formFields);
- return formFieldKey ?
- fieldGroup.attributes.includes(formFieldKey) :
- false;
- }),
- expressionProperties: {
- 'templateOptions.collapsibleFieldGroupsCollapsed': (model:any, formState:any, field:FormlyFieldConfig) => {
- // Uncollapse field groups when the form has errors and is submitted
- if (
- field.type !== 'formly-group' ||
- !field.templateOptions?.collapsibleFieldGroups ||
- !field.templateOptions?.collapsibleFieldGroupsCollapsed
- ) {
- return;
- } else {
- return !(
- field.fieldGroup?.some(groupField =>
- groupField?.formControl?.errors &&
- !groupField.hide &&
- field.options?.parentForm?.submitted
- ));
- }
+ if (fieldGroup.settings) {
+ newFormFieldGroup = {
+ ...newFormFieldGroup,
+ templateOptions: {
+ ...newFormFieldGroup.templateOptions,
+ ...fieldGroup.settings.templateOptions && fieldGroup.settings.templateOptions,
},
+ expressionProperties: {
+ ...newFormFieldGroup.expressionProperties,
+ ...fieldGroup.settings.expressionProperties && fieldGroup.settings.expressionProperties,
+ }
}
}
- if (newFormFieldGroup.fieldGroup.length) {
+ if (newFormFieldGroup?.fieldGroup?.length) {
formWithFieldGroups = [...formWithFieldGroups, newFormFieldGroup];
}
return formWithFieldGroups;
}, []);
+ }
- return [...formFieldsWithoutGroup, ...formFieldGroups];
+ private getDefaultFieldGroupSettings(fieldGroupConfig:IDynamicFieldGroupConfig, formFields:IOPFormlyFieldSettings[]):IOPFormlyFieldSettings {
+ const defaultFieldGroupSettings = {
+ wrappers: ['op-dynamic-field-group-wrapper'],
+ fieldGroupClassName: 'op-form-group',
+ templateOptions: {
+ label: fieldGroupConfig.name,
+ isFieldGroup: true,
+ collapsibleFieldGroups: true,
+ collapsibleFieldGroupsCollapsed: true,
+ },
+ fieldGroup: this.getGroupFields(fieldGroupConfig, formFields),
+ expressionProperties: {
+ 'templateOptions.collapsibleFieldGroupsCollapsed': this.collapsibleFieldGroupsCollapsedExpressionProperty
+ }
+ };
+
+ return defaultFieldGroupSettings;
+ }
+
+ private getGroupFields(fieldGroupConfig:IDynamicFieldGroupConfig, formFields:IOPFormlyFieldSettings[]) {
+ return formFields.filter(formField => {
+ const formFieldKey = formField.key && this.getFieldProperty(formField.key);
+
+ if (!formFieldKey) {
+ return false;
+ } else if (fieldGroupConfig.fieldsFilter) {
+ return fieldGroupConfig.fieldsFilter(formField);
+ } else {
+ return true;
+ }
+ })
+ }
+
+ private collapsibleFieldGroupsCollapsedExpressionProperty(model:any, formState:any, field:FormlyFieldConfig) {
+ // Uncollapse field groups when the form has errors and is submitted
+ if (
+ field.type !== 'formly-group' ||
+ !field.templateOptions?.collapsibleFieldGroups ||
+ !field.templateOptions?.collapsibleFieldGroupsCollapsed
+ ) {
+ return;
+ } else {
+ return !(
+ field.fieldGroup?.some((groupField:IOPFormlyFieldSettings) =>
+ groupField.formControl?.errors &&
+ !groupField.hide &&
+ field.options?.parentForm?.submitted
+ ));
+ }
}
}
+
diff --git a/frontend/src/app/modules/common/dynamic-forms/services/dynamic-form/dynamic-form.service.spec.ts b/frontend/src/app/modules/common/dynamic-forms/services/dynamic-form/dynamic-form.service.spec.ts
index 3814055ae52..3478934b8ae 100644
--- a/frontend/src/app/modules/common/dynamic-forms/services/dynamic-form/dynamic-form.service.spec.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/services/dynamic-form/dynamic-form.service.spec.ts
@@ -2,7 +2,6 @@ import { TestBed } from '@angular/core/testing';
import { DynamicFormService } from "core-app/modules/common/dynamic-forms/services/dynamic-form/dynamic-form.service";
import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing";
import { HttpClient } from "@angular/common/http";
-import { IOPDynamicFormSettings } from "core-app/modules/common/dynamic-forms/typings";
import { DynamicFieldsService } from "core-app/modules/common/dynamic-forms/services/dynamic-fields/dynamic-fields.service";
import { FormGroup } from "@angular/forms";
import { of } from "rxjs";
diff --git a/frontend/src/app/modules/common/dynamic-forms/spec/helpers.ts b/frontend/src/app/modules/common/dynamic-forms/spec/helpers.ts
index f889b766df7..0eb78a4a613 100644
--- a/frontend/src/app/modules/common/dynamic-forms/spec/helpers.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/spec/helpers.ts
@@ -40,7 +40,7 @@ export function createDynamicInputFixture(fields: IOPFormlyFieldSettings[], mode
model = model;
fields = fields;
- @ViewChild(FormlyForm) dynamicControl:FormlyForm;
+ @ViewChild(FormlyForm) dynamicForm:FormlyForm;
}
const notificationsServiceSpy = jasmine.createSpyObj('NotificationsService', ['addError', 'addSuccess']);
@@ -115,12 +115,12 @@ export function createDynamicInputFixture(fields: IOPFormlyFieldSettings[], mode
}
export function testDynamicInputControValueAccessor(fixture:ComponentFixture<any>, model:any, selector:string) {
- const dynamicControl: FormGroup = fixture.componentInstance.dynamicControl.form;
+ const dynamicForm: FormGroup = fixture.componentInstance.dynamicForm.form;
const dynamicInput = fixture.debugElement.query(By.css(selector)).nativeElement;
// Test ControlValueAccessor
// Write Value
- expect(dynamicControl.value.testControl).toBe(model.initialValue);
+ expect(dynamicForm.value.testControl).toBe(model.initialValue);
expect(dynamicInput.classList.contains('ng-untouched')).toBeTrue();
expect(dynamicInput.classList.contains('ng-valid')).toBeTrue();
expect(dynamicInput.classList.contains('ng-pristine')).toBeTrue();
@@ -135,7 +135,7 @@ export function testDynamicInputControValueAccessor(fixture:ComponentFixture<any
fixture.detectChanges();
- expect(dynamicControl.value.testControl).toBe(model.changedValue);
+ expect(dynamicForm.value.testControl).toBe(model.changedValue);
expect(dynamicInput.classList.contains('ng-dirty')).toBeTrue();
// Blur
@@ -144,7 +144,7 @@ export function testDynamicInputControValueAccessor(fixture:ComponentFixture<any
expect(dynamicInput.classList.contains('ng-touched')).toBeTrue();
// Disabled
- dynamicControl.disable();
+ dynamicForm.disable();
fixture.detectChanges();
expect(dynamicInput.disabled).toBeTrue();
}
\ No newline at end of file
diff --git a/frontend/src/app/modules/common/dynamic-forms/typings.d.ts b/frontend/src/app/modules/common/dynamic-forms/typings.d.ts
index ab2caf1faba..a2d6dc2d2c1 100644
--- a/frontend/src/app/modules/common/dynamic-forms/typings.d.ts
+++ b/frontend/src/app/modules/common/dynamic-forms/typings.d.ts
@@ -11,16 +11,19 @@ export interface IOPFormlyFieldSettings extends FormlyFieldConfig {
key?:string;
type?:OPInputType;
templateOptions?:IOPFormlyTemplateOptions;
+ [key:string]:any;
}
export interface IOPFormlyTemplateOptions extends FormlyTemplateOptions {
- property?: string;
- label?: string;
- hasDefault?: boolean;
+ property?:string;
+ label?:string;
+ hasDefault?:boolean;
+ fieldGroup?:string;
isFieldGroup?:boolean;
collapsibleFieldGroups?:boolean;
collapsibleFieldGroupsCollapsed?:boolean;
helpTextAttributeScope?:string;
+ showValidationErrorOn?:'change' | 'blur' | 'submit' | 'never';
}
type OPInputType = 'formattableInput'|'selectInput'|'textInput'|'integerInput'|
@@ -30,3 +33,9 @@ export interface IOPDynamicInputTypeSettings {
config:IOPFormlyFieldSettings,
useForFields:OPFieldType[];
}
+
+export interface IDynamicFieldGroupConfig {
+ name:string;
+ fieldsFilter?:(fieldProperty:IOPFormlyFieldSettings) => boolean;
+ settings?:IOPFormlyFieldSettings;
+}
diff --git a/frontend/src/app/modules/common/forms/form-field/form-field.component.ts b/frontend/src/app/modules/common/forms/form-field/form-field.component.ts
index b3d804b2632..bc04c523d5a 100644
--- a/frontend/src/app/modules/common/forms/form-field/form-field.component.ts
+++ b/frontend/src/app/modules/common/forms/form-field/form-field.component.ts
@@ -4,41 +4,36 @@ import {
HostBinding,
ContentChild,
Optional,
- OnInit,
} from "@angular/core";
import {
NgControl,
AbstractControl,
FormGroupDirective,
} from "@angular/forms";
-import { FormlyField } from "@ngx-formly/core";
-import { DynamicFormComponent } from "core-app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component";
@Component({
selector: 'op-form-field',
templateUrl: './form-field.component.html',
})
-export class OpFormFieldComponent implements OnInit{
+export class OpFormFieldComponent {
@HostBinding('class.op-form-field') className = true;
@HostBinding('class.op-form-field_invalid') get errorClassName() {
return this.showErrorMessage;
}
@Input() label = '';
- @Input() set helpTextAttribute(helpTextAttribute:string|undefined) {
- this._helpTextAttribute = helpTextAttribute;
- };
- @Input() set helpTextAttributeScope(helpTextAttributeScope:string|undefined) {
- this._helpTextAttributeScope = helpTextAttributeScope;
- };
@Input() noWrapLabel = true;
@Input() required = false;
- @Input() showValidationErrorOn: 'change' | 'blur' | 'submit' | 'never';
+ @Input() hidden = false;
+ @Input() showValidationErrorOn:'change' | 'blur' | 'submit' | 'never' = 'submit';
+ @Input() control?:AbstractControl;
+ @Input() helpTextAttribute?:string;
+ @Input() helpTextAttributeScope?:string;
@ContentChild(NgControl) ngControl:NgControl;
- get formControl ():AbstractControl|undefined|null {
- return this.ngControl?.control || this._dynamicControl?.field?.formControl;
+ get formControl():AbstractControl|undefined|null {
+ return this.ngControl?.control || this.control;
}
get showErrorMessage():boolean {
@@ -59,30 +54,7 @@ export class OpFormFieldComponent implements OnInit{
return showErrorMessage;
}
- get hidden () {
- return this._dynamicControl?.field?.hide;
- }
-
- get helpTextAttribute() {
- return this._helpTextAttribute || this._dynamicControl?.field?.templateOptions?.property;
- }
-
- get helpTextAttributeScope() {
- return this._helpTextAttributeScope || this._dynamicFormComponent?.helpTextAttributeScope;
- }
-
- private _helpTextAttribute:string|undefined;
- private _helpTextAttributeScope:string|undefined;
-
constructor(
@Optional() private _formGroupDirective:FormGroupDirective,
- @Optional() private _dynamicFormComponent:DynamicFormComponent,
- @Optional() private _dynamicControl:FormlyField,
) {}
-
- ngOnInit() {
- this.showValidationErrorOn = this.showValidationErrorOn ||
- this._dynamicFormComponent?.showValidationErrorsOn ||
- 'submit';
- }
}
diff --git a/frontend/src/app/modules/fields/edit/field-types/formattable-edit-field/formattable-edit-field.component.html b/frontend/src/app/modules/fields/edit/field-types/formattable-edit-field/formattable-edit-field.component.html
new file mode 100644
index 00000000000..5310f527d4b
--- /dev/null
+++ b/frontend/src/app/modules/fields/edit/field-types/formattable-edit-field/formattable-edit-field.component.html
@@ -0,0 +1,18 @@
+<div class="textarea-wrapper">
+ <div class="op-ckeditor--wrapper op-ckeditor-element">
+ <op-ckeditor [context]="ckEditorContext"
+ [content]="initialContent"
+ (onContentChange)="onContentChange($event)"
+ (onInitializationFailed)="initializationError = true"
+ (onInitialized)="onCkeditorSetup($event)"
+ [ckEditorType]="editorType">
+ </op-ckeditor>
+ </div>
+ <edit-field-controls *ngIf="!(handler.inEditMode || initializationError)"
+ [fieldController]="field"
+ (onSave)="handleUserSubmit()"
+ (onCancel)="handler.handleUserCancel()"
+ [saveTitle]="text.save"
+ [cancelTitle]="text.cancel">
+ </edit-field-controls>
+</div>
\ No newline at end of file
diff --git a/frontend/src/app/modules/fields/edit/field-types/formattable-edit-field/formattable-edit-field.component.ts b/frontend/src/app/modules/fields/edit/field-types/formattable-edit-field/formattable-edit-field.component.ts
index 560d8554d17..3ec98abe686 100644
--- a/frontend/src/app/modules/fields/edit/field-types/formattable-edit-field/formattable-edit-field.component.ts
+++ b/frontend/src/app/modules/fields/edit/field-types/formattable-edit-field/formattable-edit-field.component.ts
@@ -30,29 +30,8 @@ import { EditFieldComponent } from "core-app/modules/fields/edit/edit-field.comp
import { OpCkeditorComponent } from "core-app/modules/common/ckeditor/op-ckeditor.component";
import { ICKEditorContext, ICKEditorInstance } from "core-app/modules/common/ckeditor/ckeditor-setup.service";
-export const formattableFieldTemplate = `
- <div class="textarea-wrapper">
- <div class="op-ckeditor--wrapper op-ckeditor-element">
- <op-ckeditor [context]="ckEditorContext"
- [content]="rawValue"
- (onContentChange)="onContentChange($event)"
- (onInitializationFailed)="initializationError = true"
- (onInitialized)="onCkeditorSetup($event)"
- [ckEditorType]="editorType">
- </op-ckeditor>
- </div>
- <edit-field-controls *ngIf="!(handler.inEditMode || initializationError)"
- [fieldController]="field"
- (onSave)="handleUserSubmit()"
- (onCancel)="handler.handleUserCancel()"
- [saveTitle]="text.save"
- [cancelTitle]="text.cancel">
- </edit-field-controls>
- </div>
-`;
-
@Component({
- template: formattableFieldTemplate,
+ templateUrl: "./formattable-edit-field.component.html",
changeDetection: ChangeDetectionStrategy.OnPush
})
export class FormattableEditFieldComponent extends EditFieldComponent implements OnInit {
@@ -67,6 +46,7 @@ export class FormattableEditFieldComponent extends EditFieldComponent implements
public isPreview = false;
public previewHtml = '';
public text:any = {};
+ public initialContent:string;
public editorType = this.resource.getEditorTypeFor(this.field.name);
@@ -150,6 +130,8 @@ export class FormattableEditFieldComponent extends EditFieldComponent implements
}
protected initialize() {
+ this.initialContent = this.rawValue;
+
if (this.resource.isNew && this.editor) {
// Reset CKEditor when reloading after type/form changes
this.reset();
diff --git a/frontend/src/app/modules/projects/components/copy-project/copy-project.component.html b/frontend/src/app/modules/projects/components/copy-project/copy-project.component.html
index 387cb774823..a77737625ce 100644
--- a/frontend/src/app/modules/projects/components/copy-project/copy-project.component.html
+++ b/frontend/src/app/modules/projects/components/copy-project/copy-project.component.html
@@ -1,6 +1,7 @@
<op-dynamic-form
[formUrl]="formUrl"
[fieldsSettingsPipe]="dynamicFieldsSettingsPipe"
+ [fieldGroups]="fieldGroups"
(submitted)="onSubmitted($event)"
helpTextAttributeScope="Project"
></op-dynamic-form>
\ No newline at end of file
diff --git a/frontend/src/app/modules/projects/components/copy-project/copy-project.component.ts b/frontend/src/app/modules/projects/components/copy-project/copy-project.component.ts
index 13fb5f30105..cd5e8e669b1 100644
--- a/frontend/src/app/modules/projects/components/copy-project/copy-project.component.ts
+++ b/frontend/src/app/modules/projects/components/copy-project/copy-project.component.ts
@@ -1,20 +1,17 @@
-import {ChangeDetectionStrategy, Component, OnInit} from '@angular/core';
+import {Component, OnInit} from '@angular/core';
import {StateService, UIRouterGlobals} from "@uirouter/core";
import {UntilDestroyedMixin} from "core-app/helpers/angular/until-destroyed.mixin";
import {PathHelperService} from "core-app/modules/common/path-helper/path-helper.service";
import {HalSource} from "core-app/modules/hal/resources/hal-resource";
-import {IOPFormlyFieldSettings, IOPFormlyTemplateOptions} from "core-app/modules/common/dynamic-forms/typings";
+import {
+ IDynamicFieldGroupConfig,
+ IOPFormlyFieldSettings,
+ IOPFormlyTemplateOptions,
+} from "core-app/modules/common/dynamic-forms/typings";
import {I18nService} from "core-app/modules/common/i18n/i18n.service";
import {APIV3Service} from "core-app/modules/apiv3/api-v3.service";
import {JobStatusModal} from "core-app/modules/job-status/job-status-modal/job-status.modal";
import {OpModalService} from "core-app/modules/modal/modal.service";
-import {ProjectFormAttributeGroups} from "core-app/modules/projects/form-helpers/form-attribute-groups";
-
-interface CopyFormFieldConfig {
- firstLevelFields:IOPFormlyFieldSettings[];
- metaLevelFields:IOPFormlyFieldSettings[];
- advancedSettingsFields:IOPFormlyFieldSettings[];
-}
@Component({
selector: 'op-copy-project',
@@ -22,6 +19,7 @@ interface CopyFormFieldConfig {
})
export class CopyProjectComponent extends UntilDestroyedMixin implements OnInit {
dynamicFieldsSettingsPipe = this.fieldSettingsPipe.bind(this);
+ fieldGroups:IDynamicFieldGroupConfig[];
formUrl:string;
@@ -48,6 +46,16 @@ export class CopyProjectComponent extends UntilDestroyedMixin implements OnInit
ngOnInit():void {
this.formUrl = this.apiV3Service.projects.id(this.uIRouterGlobals.params.projectPath).copy.form.path;
+ this.fieldGroups = [
+ {
+ name: this.text.advancedSettingsLabel,
+ fieldsFilter: (field:IOPFormlyFieldSettings) => !this.isMeta(field.templateOptions?.property) && !this.isPrimaryAttribute(field.templateOptions),
+ },
+ {
+ name: this.text.copySettingsLabel,
+ fieldsFilter: (field:IOPFormlyFieldSettings) => this.isMeta(field.templateOptions?.property),
+ },
+ ];
}
onSubmitted(response:HalSource) {
@@ -59,38 +67,14 @@ export class CopyProjectComponent extends UntilDestroyedMixin implements OnInit
}
private fieldSettingsPipe(dynamicFieldsSettings:IOPFormlyFieldSettings[]):IOPFormlyFieldSettings[] {
- const fieldsLayoutConfig = dynamicFieldsSettings
- .reduce((result, field) => {
- field = {
- ...field,
- hide: this.isHiddenField(field.key),
- }
-
- const to = field.templateOptions;
- if (this.isMeta(to?.property)) {
- result.metaLevelFields = [...result.metaLevelFields, field];
- } else if (to && this.isPrimaryAttribute(to)) {
- result.firstLevelFields = [...result.firstLevelFields, field];
- } else {
- result.advancedSettingsFields = [...result.advancedSettingsFields, field];
- }
-
- return result;
- }, {
- firstLevelFields: [],
- metaLevelFields: [],
- advancedSettingsFields: []
- } as CopyFormFieldConfig
- );
-
- return [
- ...fieldsLayoutConfig.firstLevelFields,
- ProjectFormAttributeGroups.collapsibleFieldset(fieldsLayoutConfig.advancedSettingsFields, this.text.advancedSettingsLabel),
- ProjectFormAttributeGroups.collapsibleFieldset(fieldsLayoutConfig.metaLevelFields, this.text.copySettingsLabel),
- ];
+ return dynamicFieldsSettings.map(field => ({...field, hide: this.isHiddenField(field.key)}))
}
- private isPrimaryAttribute(to:IOPFormlyTemplateOptions):boolean {
+ private isPrimaryAttribute(to?:IOPFormlyTemplateOptions):boolean {
+ if (!to) {
+ return false;
+ }
+
return (to.required &&
!to.hasDefault &&
to.payloadValue == null) ||
diff --git a/frontend/src/app/modules/projects/components/new-project/new-project.component.html b/frontend/src/app/modules/projects/components/new-project/new-project.component.html
index 29152922c7a..cb106276065 100644
--- a/frontend/src/app/modules/projects/components/new-project/new-project.component.html
+++ b/frontend/src/app/modules/projects/components/new-project/new-project.component.html
@@ -25,6 +25,7 @@
[resourcePath]="resourcePath"
[initialPayload]="initialPayload"
[fieldsSettingsPipe]="dynamicFieldsSettingsPipe"
+ [fieldGroups]="fieldGroups"
(submitted)="onSubmitted($event)"
helpTextAttributeScope="Project"
></op-dynamic-form>
\ No newline at end of file
diff --git a/frontend/src/app/modules/projects/components/new-project/new-project.component.ts b/frontend/src/app/modules/projects/components/new-project/new-project.component.ts
index eed5f3262bb..84d3238485d 100644
--- a/frontend/src/app/modules/projects/components/new-project/new-project.component.ts
+++ b/frontend/src/app/modules/projects/components/new-project/new-project.component.ts
@@ -1,9 +1,9 @@
-import {Component, OnInit} from '@angular/core';
+import { Component, OnInit, ViewChild } from '@angular/core';
import {StateService, UIRouterGlobals} from "@uirouter/core";
import {UntilDestroyedMixin} from "core-app/helpers/angular/until-destroyed.mixin";
import {PathHelperService} from "core-app/modules/common/path-helper/path-helper.service";
import {HalResource, HalSource} from "core-app/modules/hal/resources/hal-resource";
-import {IOPFormlyFieldSettings} from "core-app/modules/common/dynamic-forms/typings";
+import {IDynamicFieldGroupConfig, IOPFormlyFieldSettings} from "core-app/modules/common/dynamic-forms/typings";
import {I18nService} from "core-app/modules/common/i18n/i18n.service";
import {FormControl, FormGroup} from "@angular/forms";
import {APIV3Service} from "core-app/modules/apiv3/api-v3.service";
@@ -12,7 +12,7 @@ import {map} from "rxjs/operators";
import {Observable} from "rxjs";
import {JobStatusModal} from "core-app/modules/job-status/job-status-modal/job-status.modal";
import {OpModalService} from "core-app/modules/modal/modal.service";
-import {ProjectFormAttributeGroups} from "core-app/modules/projects/form-helpers/form-attribute-groups";
+import { DynamicFormComponent } from "core-app/modules/common/dynamic-forms/components/dynamic-form/dynamic-form.component";
export interface ProjectTemplateOption {
href:string|null;
@@ -25,12 +25,12 @@ export interface ProjectTemplateOption {
styleUrls: ['./new-project.component.sass'],
})
export class NewProjectComponent extends UntilDestroyedMixin implements OnInit {
+ formUrl:string|null;
resourcePath:string;
dynamicFieldsSettingsPipe = this.fieldSettingsPipe.bind(this);
-
+ fieldGroups:IDynamicFieldGroupConfig[];
initialPayload = {};
- formUrl:string;
text = {
use_template: this.I18n.t('js.project.use_template'),
no_template_selected: this.I18n.t('js.project.no_template_selected'),
@@ -66,6 +66,8 @@ export class NewProjectComponent extends UntilDestroyedMixin implements OnInit {
return this.templateForm.get('template');
}
+ @ViewChild(DynamicFormComponent) dynamicForm:DynamicFormComponent;
+
constructor(
private apiV3Service:APIV3Service,
private uIRouterGlobals:UIRouterGlobals,
@@ -79,6 +81,13 @@ export class NewProjectComponent extends UntilDestroyedMixin implements OnInit {
ngOnInit():void {
this.resourcePath = this.pathHelperService.projectsPath();
+ this.fieldGroups = [{
+ name: this.text.advancedSettingsLabel,
+ fieldsFilter: (field) => !['name', 'parent'].includes(field.templateOptions?.property!) &&
+ !(field.templateOptions?.required &&
+ !field.templateOptions.hasDefault &&
+ field.templateOptions.payloadValue == null),
+ }];
if (this.uIRouterGlobals.params.parent_id) {
this.setParentAsPayload(this.uIRouterGlobals.params.parent_id);
@@ -94,11 +103,11 @@ export class NewProjectComponent extends UntilDestroyedMixin implements OnInit {
}
onTemplateSelected(selected:{ href:string|null }) {
- if (selected.href) {
- this.formUrl = selected.href + '/copy';
- } else {
- this.resourcePath = this.pathHelperService.projectsPath();
+ this.initialPayload = {
+ ...this.initialPayload,
+ name: this.dynamicForm.model.name,
}
+ this.formUrl = selected?.href ? `${selected.href}/copy` : null;
}
private isHiddenField(key:string|undefined):boolean {
@@ -122,34 +131,6 @@ export class NewProjectComponent extends UntilDestroyedMixin implements OnInit {
}
private fieldSettingsPipe(dynamicFieldsSettings:IOPFormlyFieldSettings[]):IOPFormlyFieldSettings[] {
- const fieldsLayoutConfig = dynamicFieldsSettings
- .reduce((result, field) => {
- field = {
- ...field,
- hide: this.isHiddenField(field.key),
- }
-
- if (
- (field.templateOptions?.required &&
- !field.templateOptions.hasDefault &&
- field.templateOptions.payloadValue == null) ||
- field.templateOptions?.property === 'name' ||
- field.templateOptions?.property === 'parent'
- ) {
- result.firstLevelFields = [...result.firstLevelFields, field];
- } else {
- result.advancedSettingsFields = [...result.advancedSettingsFields, field];
- }
-
- return result;
- }, {
- firstLevelFields: [],
- advancedSettingsFields: []
- } as { firstLevelFields:IOPFormlyFieldSettings[], advancedSettingsFields:IOPFormlyFieldSettings[] });
-
- return [
- ...fieldsLayoutConfig.firstLevelFields,
- ProjectFormAttributeGroups.collapsibleFieldset(fieldsLayoutConfig.advancedSettingsFields, this.text.advancedSettingsLabel),
- ];
+ return dynamicFieldsSettings.map(field => ({...field, hide: this.isHiddenField(field.key)}))
}
}
diff --git a/frontend/src/app/modules/projects/components/projects/projects.component.ts b/frontend/src/app/modules/projects/components/projects/projects.component.ts
index 2d2ec6d61ef..7b96e1bd9de 100644
--- a/frontend/src/app/modules/projects/components/projects/projects.component.ts
+++ b/frontend/src/app/modules/projects/components/projects/projects.component.ts
@@ -30,7 +30,7 @@ export class ProjectsComponent extends UntilDestroyedMixin implements OnInit {
this.resourceId = this._uIRouterGlobals.params.projectPath;
this.dynamicFieldsSettingsPipe = (dynamicFieldsSettings) => {
return dynamicFieldsSettings
- .reduce((formattedDynamicFieldsSettings, dynamicFormField) => {
+ .reduce((formattedDynamicFieldsSettings:IOPFormlyFieldSettings[], dynamicFormField) => {
if (this.isFieldHidden(dynamicFormField.key)) {
dynamicFormField = {
...dynamicFormField,
diff --git a/frontend/src/app/modules/projects/form-helpers/form-attribute-groups.ts b/frontend/src/app/modules/projects/form-helpers/form-attribute-groups.ts
index 22913bdffe2..e69de29bb2d 100644
--- a/frontend/src/app/modules/projects/form-helpers/form-attribute-groups.ts
+++ b/frontend/src/app/modules/projects/form-helpers/form-attribute-groups.ts
@@ -1,47 +0,0 @@
-import {IOPFormlyFieldSettings} from "core-app/modules/common/dynamic-forms/typings";
-import {FormlyFieldConfig} from "@ngx-formly/core";
-
-export namespace ProjectFormAttributeGroups {
-
- /**
- * Create a collapsible formly fieldset for the given fields
- * @param {IOPFormlyFieldSettings[]} fields Fields to include in the fieldset
- * @param {string} label Label of the fieldset
- */
- export function collapsibleFieldset(
- fields:IOPFormlyFieldSettings[],
- label:string,
- ):IOPFormlyFieldSettings {
- return {
- fieldGroup: fields,
- fieldGroupClassName: "op-form--fieldset",
- templateOptions: {
- label: label,
- isFieldGroup: true,
- collapsibleFieldGroups: true,
- collapsibleFieldGroupsCollapsed: true,
- },
- type: "formly-group" as "formly-group",
- wrappers: ["op-dynamic-field-group-wrapper"],
- expressionProperties: {
- 'templateOptions.collapsibleFieldGroupsCollapsed': (model:unknown, formState:unknown, field:FormlyFieldConfig) => {
- // Uncollapse field groups when the form has errors and has been submitted
- if (
- field.type !== 'formly-group' ||
- !field.templateOptions?.collapsibleFieldGroups ||
- !field.templateOptions?.collapsibleFieldGroupsCollapsed
- ) {
- return;
- } else {
- return !(
- field.fieldGroup?.some(groupField =>
- groupField?.formControl?.errors &&
- !groupField.hide &&
- field.options?.parentForm?.submitted
- ));
- }
- },
- }
- };
- }
-}
\ No newline at end of file
diff --git a/spec/features/projects/projects_spec.rb b/spec/features/projects/projects_spec.rb
index b5465c4a8c9..f4da641395f 100644
--- a/spec/features/projects/projects_spec.rb
+++ b/spec/features/projects/projects_spec.rb
@@ -50,10 +50,36 @@ describe 'Projects', type: :feature, js: true do
name_field.set_value 'Foo bar'
click_button 'Save'
+ sleep 1
+
expect(page).to have_content 'Foo bar'
expect(page).to have_current_path /\/projects\/foo-bar\/?/
end
+ it 'can create a subproject' do
+ click_on project.name
+ SeleniumHubWaiter.wait
+ click_on 'Project settings'
+ SeleniumHubWaiter.wait
+ click_on 'New subproject'
+
+ name_field.set_value 'Foo child'
+
+ sleep 1
+
+ parent_field.expect_selected project.name
+
+ click_button 'Save'
+
+ sleep 1
+
+ expect(page).to have_current_path /\/projects\/foo-child\/?/
+
+ child = Project.last
+ expect(child.identifier).to eq 'foo-child'
+ expect(child.parent).to eq project
+ end
+
it 'does not create a project with an already existing identifier' do
click_on 'New project'
diff --git a/spec/support/capybara.rb b/spec/support/capybara.rb
index b5c6125b18a..5f9403a6f3a 100644
--- a/spec/support/capybara.rb
+++ b/spec/support/capybara.rb
@@ -44,6 +44,9 @@ if ENV['CAPYBARA_AWS_ACCESS_KEY_ID']
},
bucket_name: ENV.fetch('CAPYBARA_AWS_BUCKET', 'openproject-ci-public-logs')
}
+ Capybara::Screenshot.s3_object_configuration = {
+ acl: 'public-read'
+ }
end
Rails.application.config do