Creating accurate JSON data using p-dropdown PrimeNG

I recently started learning Angular and encountered a situation while using the Java API:

In my Release class, the category is not required (class Category).

@Entity
@Table(name = "release")
public class Release {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    private String description;

    @ManyToOne
    @JoinColumn(name = "id_category")
    private Category;

    (...)
}

When attempting to register a release through an Angular-created page using the REST API, I send the following json:

{"description": "test", "category": {}}

Since the category is not provided, my API in Java returns the error:

TransientObjectException - object references an unsaved transient instance - save the transient instance before flushing

To test this, I used Postman and successfully registered a release without specifying the category as follows:

{"description": "test"}

This leads me to question whether the issue lies in the Angular code that utilizes the p-dropdown component from PrimeNG:

<p-dropdown placeholder="Select ..." [autoWidth]="false"
      [filter]="true" [options]="categories"
      [(ngModel)]="release.category.id" name="category"
      #category="ngModel"> </p-dropdown>

Or could it be related to how the category is declared in the Release class?

Upon registering a release with the specified category, there are no errors and the json looks like this:

{"description": "test", "category": {"id": 1}}

Any insights would be appreciated. Thank you!

Answer №1

When it comes to p-dropdown options, it's crucial that you pass in an Array instead of an object.

{"description": "test", "category": {}}

The correct format should be:

{"description": "test", "category": [{"name":"John", "id": "1"},{"name":"Kan", "id": "2"}]}

This way, the array will be accepted as an option.

Make sure to utilize the optionLabel property to specify which key you want to display in the list.

<p-dropdown placeholder = "Select ..." [autoWidth] = "false"
  [filter] = "true" [options] = "categories"
  [(ngModel)] = "release.category.id" name = "category"
  #category = "ngModel" [optionLabel]="name"> </ p-dropdown>

In this scenario, your ngModel will contain the entire object if the user selects it.

{"name":"John", "id": "1"}

If you wish for it to return a single value '1' when the user selects John, you'll need to adjust the option Array like so:

[{"label":"John", "value": "1"},{"label":"Kan", "value": "2"}

I hope this explanation helps clarify things!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging external data for testing in Protractor script

I am encountering an issue while attempting to access test data using JSON, as it keeps showing up as undefined. I am implementing a Page Object Model and trying to reference external test data. However, when passing the values from my test data into a fun ...

Discover the smallest value in a 2D array of strings using Java

For my assignment, I am working with a 2D array of strings that contains student names, courses/subjects, and the marks each student received in each course. The goal is to identify the lowest mark in each course. For example, in Math: Student A scored 78, ...

Obtain data in JSON format through an xmlhttp request

I originally used jQuery for this task, but I now want to switch to regular JavaScript as I'll be incorporating it into phonegap. I aim to avoid relying on different JS frameworks every time I make a server request, which could potentially improve per ...

Is it necessary to run npm init every instance I initiate a fresh project?

In a recent practice project, I noticed that the package.json file was automatically created when I used npx create-react-app ..., even though some people say running npm init is required for creating it. Can someone explain this to me, please? ...

Tips for incorporating a mesh into Forge Viewer v6 with Typescript

Is there a way to add meshes to Forge Viewer v6 using Type script? I've tried various methods that worked with v4, but I'm encountering issues now. private wallGeometry: THREE.BoxBufferGeometry; drawWalls() { ...

Unlock the secret to retrieving specific properties from a JSON object

Whenever this code is executed: import requests import json def obtain_sole_fact(): catFact = requests.get("https://catfact.ninja/fact?max_length=140") json_data = json.loads(catFact.text) return json_data['fact'] print(obtain_s ...

Retrieving both keys and values from a response list in Zabbix API using Python 3

There is an issue I am facing while working with data from zabbix. I have constructed a request as shown below: requests = zapi.host.get({"output": ZabbixApiValues, "selectInventory": ZabbixApiValues, "filter": {"host&quo ...

Using setState as a parameter in a personalized hook in React/Next.js while incorporating TypeScript

I encountered an issue with the following code snippet: import { useState, useEffect } from "react"; type Props = { setState: (value: string) => void; }; const useSomeCustomHook = ({ setState }: Props) => { useEffect(() => { se ...

A practical guide to troubleshooting typescript errors when exporting a map component

I encountered a typescript error when trying to export the map component with GoogleApiWrapper. It works fine when not wrapped in GoogleApiWrapper, but all my attempts to resolve the issue have failed. I would appreciate it if someone could review the code ...

FrisbyJS and JSONSchema encounter a SchemaError when the specified schema does not exist

I utilize frisbyjs along with modules like jsonschema and jasmine-node for execution. There is a particular schema named test.json: { "error": { "type": "array", "minItems": 2, "items": { "type": "object", "properties": { ...

"An in-depth guide on parsing JSON and showcasing it in an HTML format

As part of my order processing, I am saving the order details into a JSON file named order_details.json. Here is an example of how the data is structured: [{ "uniqueID": "CHECKOUT_IE01", "orderID": "4001820182", "date": "06-02-2019 16:55:32.32 ...

"Incorporating the node_modules folder into the Express.js compilation process

Is there a way to automatically include dependencies during Express.js compilation, similar to building a React project? I want to avoid dealing with dependencies after the build process. Any suggestions on how to achieve this? I have not attempted any so ...

Type A can be assigned to the limitation of type T, although T may be instantiated with a varying subtype constraint of either A or B

I keep receiving this confusing error from TypeScript. My T generic should be fully compatible with types A | B since it extends from it! The error is incorrect in saying that you can't instantiate it with an incompatible type. type MyProps<T exten ...

Transforming a jsonObject into a JavaScript array

I am working with a JSON object and I need to extract data from it to create an array. Here is an example of the desired array: ['city 1','city 2','city ..'] Below is the JSON output: {"\u0000*\u0000_data":[{"id": ...

Conditionally typing in TypeScript to check if a string contains a specific value

Looking to create a function that takes a string as input and determines whether it contains '[]' or not. If it does, the function should return a list, otherwise an object. This is what I have so far: function customFunction<T = any>(input ...

TypeError: "Table" has not been declared

This is my first experience with the script editor. I have been given the task of creating a pivot table for Google Sheets using a script. // This script creates a pivot table in Google Sheets function createPivotTable() { var ss = SpreadsheetApp.getAc ...

What is the best way to include the input object in a JSON array?

In the process of creating a weather forecasting console application, I have encountered an issue regarding saving user input locations. The user is asked if they would like to save the longitude and latitude input, which are then stored in a JSON file. Th ...

The error message "java.sql.SQLException: Parameter number 2 is not designated as an OUT parameter"

I encountered an issue while trying to execute the following code: 1. cs = getCon1().prepareCall("{CALL SaveLabourWageDetails(?,?)}"); 2. cs.setString(1, user.getUserId()); 3. cs.registerOutParameter(2, java.sql.Types.INTEGER); //<--- Error occurs he ...

Exploring ways to extract various elements from a JSON document using Python

I am currently developing a Python program that retrieves bus schedules from a server and displays them. The JSON data structure is as follows: { "errorcode": "0", "errormessage": "", "numberofresults": 4, "stopid": "175", "timestamp": "28/09/2016 10:32:4 ...

Can TypeScript be used to generate a union type that includes all the literal values from an input string array?

Is it feasible to create a function in TypeScript that takes an array of strings and returns a string union? Consider the following example function: function myfn(strs: string[]) { return strs[0]; } If I use this function like: myfn(['a', &a ...