Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

angular: when creating, resolve routing to null #19024

Merged
merged 1 commit into from
Jun 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ for (field of fieldsToGenerate) {
}
}
for (relationship of relationships) {
const relationshipType = relationship.relationshipType
const { relationshipType, joinColumnNames } = relationship;
if (
(relationshipType === "many-to-one"
|| (relationshipType === "one-to-one" && relationship.ownerSide === true
&& (relationship.id == null || relationship.id === false))
) && (relationship.relationshipValidate === true && relationship.relationshipRequired)
) {
header.push(getColumnName(relationship.relationshipName) + "_id");
header.push(joinColumnNames[0]);
}
}
table.push(header);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ describe('<%= entityAngularName %> routing resolve service', () => {
let mockActivatedRouteSnapshot: ActivatedRouteSnapshot;
let routingResolveService: <%= entityAngularName %>RoutingResolveService;
let service: <%= entityAngularName %>Service;
let result<%= entityAngularName %>: I<%= entityAngularName %> | undefined;
let result<%= entityAngularName %>: I<%= entityAngularName %> | null | undefined;

beforeEach(() => {
TestBed.configureTestingModule({
Expand Down Expand Up @@ -76,7 +76,7 @@ describe('<%= entityAngularName %> routing resolve service', () => {
expect(result<%= entityAngularName %>).toEqual({ <%= primaryKey.name %>: <%- tsKeyId %> });
});

it('should return new I<%= entityAngularName %> if id is not provided', () => {
it('should return null if id is not provided', () => {
// GIVEN
service.find = jest.fn();
mockActivatedRouteSnapshot.params = {};
Expand All @@ -88,7 +88,7 @@ describe('<%= entityAngularName %> routing resolve service', () => {

// THEN
expect(service.find).not.toBeCalled();
expect(result<%= entityAngularName %>).toEqual(new <%= entityAngularName %>());
expect(result<%= entityAngularName %>).toEqual(null);
});

it('should route to 404 page if data not found in server', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,18 @@ import { Resolve, ActivatedRouteSnapshot, Router } from '@angular/router';
import { Observable, of, EMPTY } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

import { I<%= entityAngularName %>, <%= entityAngularName %> } from '../<%= entityFileName %>.model';
import { I<%= entityAngularName %> } from '../<%= entityFileName %>.model';
import { <%= entityAngularName %>Service } from '../service/<%= entityFileName %>.service';

@Injectable({ providedIn: 'root' })
export class <%= entityAngularName %>RoutingResolveService implements Resolve<I<%= entityAngularName %>> {
export class <%= entityAngularName %>RoutingResolveService implements Resolve<I<%= entityAngularName %> | null> {
constructor(protected service: <%= entityAngularName %>Service, protected router: Router) {}

resolve(route: ActivatedRouteSnapshot): Observable<I<%= entityAngularName %>> | Observable<never> {
resolve(route: ActivatedRouteSnapshot): Observable<I<%= entityAngularName %> | null | never> {
const id = route.params['<%= primaryKey.name %>'];
if (id) {
return this.service.find(id).pipe(
mergeMap((<%= entityInstance %>: HttpResponse<<%= entityAngularName %>>) => {
mergeMap((<%= entityInstance %>: HttpResponse<I<%= entityAngularName %>>) => {
if (<%= entityInstance %>.body) {
return of(<%= entityInstance %>.body);
} else {
Expand All @@ -43,6 +43,6 @@ export class <%= entityAngularName %>RoutingResolveService implements Resolve<I<
})
);
}
return of(new <%= entityAngularName %>());
return of(null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
}
_%>

<div class="row mb-3"<% if (field.autoGenerate) { %> [hidden]="editForm.get('<%= primaryKey.name %>')!.value == null"<% } %>>
<div class="row mb-3"<% if (field.autoGenerate) { %> *ngIf="editForm.get('<%= field.fieldName %>')"<% } %>>
<label class="form-label" <%= jhiPrefix %>Translate="<%= translationKey %>" for="field_<%= fieldName %>"<% if (field.javadoc) { if (enableTranslation) { %> [ngbTooltip]="'<%= i18nKeyPrefix %>.help.<%= fieldName %>' | translate"<% } else { %> ngbTooltip="<%= field.javadoc %>"<% } } %>><%= fieldNameHumanized %></label>
<%_ if (field.fieldIsEnum) { _%>
<select class="form-control" name="<%= fieldName %>" formControlName="<%= fieldName %>" id="field_<%= fieldName %>" data-cy="<%= fieldName %>">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,10 +197,10 @@ describe('<%= entityAngularName %> Management Update Component', () => {
it('Should call create service on save for new entity', () => {
// GIVEN
const saveSubject = new Subject<HttpResponse<<%= entityAngularName %>>>();
const <%= entityInstance %> = new <%= entityAngularName %>();
const <%= entityInstance %> = <%- testEntityPrimaryKey0 %>;
jest.spyOn(<%= entityInstance %>Service, 'create').mockReturnValue(saveSubject);
jest.spyOn(comp, 'previousState');
activatedRoute.data = of({ <%= entityInstance %> });
activatedRoute.data = of({ <%= entityInstance %>: null });
comp.ngOnInit();

// WHEN
Expand All @@ -210,7 +210,7 @@ describe('<%= entityAngularName %> Management Update Component', () => {
saveSubject.complete();

// THEN
expect(<%= entityInstance %>Service.create).toHaveBeenCalledWith(<%= entityInstance %>);
expect(<%= entityInstance %>Service.create).toHaveBeenCalled();
expect(comp.isSaving).toEqual(false);
expect(comp.previousState).toHaveBeenCalled();
});
Expand All @@ -230,7 +230,7 @@ describe('<%= entityAngularName %> Management Update Component', () => {
saveSubject.error('This is an error!');

// THEN
expect(<%= entityInstance %>Service.update).toHaveBeenCalledWith(<%= entityInstance %>);
expect(<%= entityInstance %>Service.update).toHaveBeenCalled();
expect(comp.isSaving).toEqual(false);
expect(comp.previousState).not.toHaveBeenCalled();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const isValidatorsRequired = hasValidationRule || hasRequiredRelationship;
_%>
import { Component, OnInit<% if (fieldsContainImageBlob) { %>, ElementRef<% } %> } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { FormBuilder,<%_ if (isValidatorsRequired) { _%> Validators<%_ } _%> } from '@angular/forms';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { finalize<% if (relationships.some(rel => rel.ownerSide === true)) { %>, map<% } %> } from 'rxjs/operators';
Expand Down Expand Up @@ -85,6 +85,7 @@ import { <%- importedType %> } from '<%- importedPath %>';
})
export class <%= entityAngularName %>UpdateComponent implements OnInit {
isSaving = false;
<%= entityInstance %>: I<%= entityAngularName %> | null = null;
<%_ enumImports.forEach( (importedPath, importedType) => { _%>
<%- _.lowerFirst(importedType) %>Values = Object.keys(<%- importedType %>);
<%_ }); _%>
Expand All @@ -101,7 +102,7 @@ export class <%= entityAngularName %>UpdateComponent implements OnInit {
<%_ } _%>

editForm = this.fb.group({
<%_ for (const field of fields) {
<%_ for (const field of fields.filter(field => !field.autoGenerate)) {
const fieldName = field.fieldName;
_%>
<%= fieldName %>: [<% if (field.fieldValidate === true) { %>null,[<% if (field.fieldValidationRequired) { %>Validators.required,<% } %><% if (field.fieldValidationMinLength) { %>Validators.minLength(<%= field.fieldValidateRulesMinlength %>),<% } %><% if (field.fieldValidationMaxLength) { %>Validators.maxLength(<%= field.fieldValidateRulesMaxlength %>),<% } %><% if (field.fieldValidationMin) { %>Validators.min(<%= field.fieldValidateRulesMin %>),<% } %><% if (field.fieldValidationMax) { %>Validators.max(<%= field.fieldValidateRulesMax %>),<% } %><% if (field.fieldValidationPattern) { %>Validators.pattern('<%= field.fieldValidateRulesPattern.replace(/\\/g, '\\\\') %>'),<% } %>]<% } %>],
Expand All @@ -118,7 +119,7 @@ _%>
<%_ if (relationship.relationshipManyToOne || (relationship.relationshipOneToOne && ownerSide)) { _%>
<%= relationshipName %>: [<% if (relationshipRequired) { %>null,Validators.required<% } %>],
<%_ } else if (relationship.relationshipManyToMany && ownerSide) { _%>
<%= relationshipFieldNamePlural %>: [<% if (relationshipRequired) { %>null,Validators.required<% } %>],
<%= relationshipFieldNamePlural %>: [[]<% if (relationshipRequired) { %>, Validators.required<% } %>],
<%_ } _%>
<%_ } _%>
});
Expand Down Expand Up @@ -150,20 +151,28 @@ _%>

ngOnInit(): void {
this.activatedRoute.data.subscribe(({ <%= entityInstance %> }) => {
this.<%= entityInstance %> = <%= entityInstance %>;

<%_ if (fieldsContainInstant || fieldsContainZonedDateTime) { _%>
if (<%= entityInstance %>.<%= primaryKey.name %> === undefined) {
if (<%= entityInstance %> == null) {
const today = dayjs().startOf('day');
<%_ for (const field of fields) {
const fieldName = field.fieldName;
<%= entityInstance %> = {
<%_ for (const field of fields.filter(field => field.fieldTypeTimed)) {
const { fieldName } = field;
_%>
<%_ if (field.fieldTypeTimed) { _%>
<%= entityInstance %>.<%= fieldName %> = today;
<%_ } _%>
<%= fieldName %>: today,
<%_ } _%>
}
};
this.editForm.patchValue(<%= entityInstance %>);
} else {
<%_ } else { _%>
if (<%= entityInstance %> != null) {
<%_ } _%>

this.updateForm(<%= entityInstance %>);
<%_ for (const field of fields.filter(field => field.autoGenerate)) { _%>
this.editForm.addControl('<%= field.fieldName %>', new FormControl(null, { validators: [Validators.required]}));
<%_ } _%>
this.updateForm(<%= entityInstance %>);
}

<%_ if (relationships.filter(rel => rel.ownerSide && !rel.otherEntityIsEmbedded).length > 0) { _%>
this.loadRelationshipsOptions();
Expand Down Expand Up @@ -209,7 +218,7 @@ _%>
save(): void {
this.isSaving = true;
const <%= entityInstance %> = this.createFromForm();
if (<%= entityInstance %>.<%= primaryKey.name %> !== undefined) {
if (<%= entityInstance %>.<%= primaryKey.name %> != null) {
this.subscribeToSaveResponse(
this.<%= entityInstance %>Service.update(<%= entityInstance %>));
} else {
Expand Down Expand Up @@ -321,9 +330,9 @@ _%>
<%= otherEntity.entityInstancePlural %>,
<%_ for (const relationship of relationshipsWithCustomSharedOptions) { _%>
<%_ if (relationship.collection) { _%>
...(this.editForm.get('<%= relationship.reference.name %>')!.value ?? []),
...(this.<%= entityInstance %>?.<%= relationship.propertyName %> ?? []),
<%_ } else { _%>
this.editForm.get('<%= relationship.reference.name %>')!.value,
this.<%= entityInstance %>?.<%= relationship.propertyName %>,
<%_ } _%>
<%_ } _%>
)))
Expand All @@ -335,7 +344,7 @@ _%>
this.<%= relationship.otherEntityName %>Service
.query({<%- filter %>})
.pipe(map((res: HttpResponse<I<%= relationship.otherEntityAngularName %>[]>) => res.body ?? []))
.pipe(map((<%= otherEntity.entityInstancePlural %>: I<%= otherEntity.entityAngularName %>[]) => this.<%= otherEntity.entityInstance %>Service.add<%= otherEntity.entityAngularName %>ToCollectionIfMissing(<%= otherEntity.entityInstancePlural %>, this.editForm.get('<%= relationship.reference.name %>')!.value)))
.pipe(map((<%= otherEntity.entityInstancePlural %>: I<%= otherEntity.entityAngularName %>[]) => this.<%= otherEntity.entityInstance %>Service.add<%= otherEntity.entityAngularName %>ToCollectionIfMissing(<%= otherEntity.entityInstancePlural %>, this.<%= entityInstance %>?.<%= relationship.propertyName %>)))
.subscribe((<%= otherEntity.entityInstancePlural %>: I<%= otherEntity.entityAngularName %>[]) => (this.<%= relationship.relationshipFieldNamePlural %>Collection = <%= otherEntity.entityInstancePlural %>));
<%_ } _%>
<%_ } _%>
Expand All @@ -345,29 +354,14 @@ _%>
protected createFromForm(): I<%= entityAngularName %> {
return {
...new <%= entityAngularName %>(),
...this.editForm.getRawValue(),
<%_ for (const field of fields) {
const fieldName = field.fieldName;
_%>
<%_ if (field.fieldTypeTimed) { _%>
<%= fieldName %>: this.editForm.get(['<%= fieldName %>'])!.value ? dayjs(this.editForm.get(['<%= fieldName %>'])!.value, DATE_TIME_FORMAT) : undefined,
<%_ } else if (field.fieldTypeBinary && !field.blobContentTypeText) { _%>
<%= fieldName %>ContentType: this.editForm.get(['<%= fieldName %>ContentType'])!.value,
<%= fieldName %>: this.editForm.get(['<%= fieldName %>'])!.value,
<%_ } else { _%>
<%= fieldName %>: this.editForm.get(['<%= fieldName %>'])!.value,
<%_ } _%>
<%_ } _%>
<%_ for (const relationship of relationships) {
const ownerSide = relationship.ownerSide;
const relationshipName = relationship.relationshipName;
const relationshipFieldNamePlural = relationship.relationshipFieldNamePlural;
_%>
<%_ if (relationship.relationshipManyToOne || (relationship.relationshipOneToOne && ownerSide)) { _%>
<%= relationshipName %>: this.editForm.get(['<%= relationshipName %>'])!.value,
<%_ } else if (relationship.relationshipManyToMany && relationship.ownerSide) { _%>
<%= relationshipFieldNamePlural %>: this.editForm.get(['<%= relationshipFieldNamePlural %>'])!.value,
<%_ } _%>
<%_ } _%>
};
} as I<%= entityAngularName %>;
}
}