Show information in a text field from JSON in SAPUI5

How can I populate a text box with data from JSON using SAPUI5?

// Sample JSON data
var data = {
    firstName: "John",
    lastName: "Doe",
    birthday: {day:01,month:05,year:1982},
    address:[{city:"Heidelberg"}],
    enabled: true
};

// Create a JSON model instance
var oModel = new sap.ui.model.json.JSONModel();
// Set the data for the model
oModel.setData(data);
// Set the model to the core
sap.ui.getCore().setModel(oModel);

// Create your controls        
var oTextView = new sap.ui.commons.TextView("textView", {
    // Bind text property of textview to firstName property in the model
    text: "{/firstName}",
    tooltip: "First Name"
});
var oTxt = new sap.ui.commons.TextField("txtField", {
    // Bind text property of textfield to firstName property in the model
    value: "{/firstName}"
});

The above code works fine, but when I move the JSON data to a separate file and try to load it, the data does not get loaded.

Currently, my JSON file looks like this:

{
  "UserDetails":[
{
  "userid": "Test-Id", 
  "sapname": "Test-SAP-Form", 
  "age": 37, 
  "annualleave": 32
}
]}

When trying to load data from the JSON file, I use the following code:

var userDetailsModel = new sap.ui.model.json.JSONModel();
userDetailsModel.loadData("json/UserDetails.json");
userDetailsModel.setData("json/UserDetails.json");
sap.ui.getCore().setModel(userDetailsModel, "UserDetails");

However, I am unable to display the data in the text box. What mistake am I making?

Answer №1

When it comes to databinding, the syntax is pretty straightforward. It involves using {model>path}. So, when you call setModel(model, "modelname"), remember to use {modelname>path}.

In your specific scenario, the necessary value is

var oTxt = new sap.ui.commons.TextField("txtField", {
    // binding the text property of a textfield to the firstName property in the model
    value: "{UserDetails>/firstName}"
});

Also, make sure to eliminate the line containing model.setData, as Qualiture pointed out in their comment.

Update: The JSON file structure differs from the path being sent to the Controls. Considering that, you should adjust the path to

{UserDetails>/UserDetails/0/firstName}

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

What is the reason behind having 3 watchers for 1 binding in AngularJS?

Take a moment to view the screenshot provided below In the screenshot, it is evident that there are #3 watchers for a single binding. Would someone care to explain the reason behind this? P.S: I am utilizing AngularJS Batarang to assess performance. ...

Guiding the user to a different React page after a successful login: a simple solution

Currently, I am working on developing my very first full-stack application with React for front-end and Node.js with Express for back-end. I have set up a /login route using react router dom where users can input their email and password ...

When we modify the prototype of the parent object, where does the __proto__ point to?

Typically, when a new object is created using the "new" keyword, the __proto__ property of the newly created object points to the prototype property of the parent class. This can be verified with the following code: function myfunc(){}; myfunc.prototype.n ...

What is the method for retrieving information from a JSON file without using a key?

Currently, I am in the process of setting up a web server using Node.js and Express. As someone who is new to this, my goal is to retrieve data from a JSON file. For instance, consider the contents of my data.json file: [{ "color": "black", ...

What is the best way to showcase content using Chakra-ui SideBar in a React Application?

After exporting the SideBar, I imported it into my App.jsx SideBar.jsx 'use client' import { IconButton, Avatar, Box, CloseButton, Flex, HStack, VStack, Icon, useColorModeValue, Text, Drawer, Draw ...

Align pictures in the middle of two divisions within a segment

This is the current code: HTML: <section class="sponsorSection"> <div class="sponsorImageRow"> <div class="sponsorImageColumn"> <img src="img/kvadrat_logo.png" class="sponsorpicture1"/> </div& ...

Adjust properties based on screen size with server-side rendering compatibility

I'm currently using the alpha branch of material-ui@v5. At the moment, I have developed a custom Timeline component that functions like this: const CustomTimeline = () => { const mdDown = useMediaQuery(theme => theme.breakpoints.down("md")); ...

The request to retrieve data from the model at http://localhost:9000/model/data.json resulted in a 404

This is the path to my directory I have a npm server running on http://localhost:9000/ to utilize the cytoscape module. However, my server is unable to locate my json file. What could be the issue with my code? This is the source code of my index.js file ...

A guide on integrating a submission button that combines values from multiple dropdown forms and redirects to a specific URL

Is there a way to make the submit button on this form act based on the combined values of two different dropdown menus? For instance, if "west" is selected from the first dropdown and "winter" is selected from the second dropdown, I want it to navigate to ...

Exploring Multilingual Autocomplete or: Best Practices for Managing Multiple Languages in Web Applications

I'm currently developing a website and I have a mysql-table named 'items' with the following structure: item_id | item (The second column is used to identify the item_id.) In a file called language1.php, I have an array that stores the it ...

Is there a way to define a type once and then use it for both a function and a component in React using TypeScript?

I have a types.ts file where I define the Redux action types, a Screen.tsx file for a component that uses the actions, and an Actions.ts file where the actions are defined. I want to find a way to declare the action type only once and then use it across bo ...

Creating a Rails partial from JSON data with a custom rake task

Currently, I am utilizing a helper function: def fetch_static_blog_posts Rails.cache.fetch("blog_posts", :expires_in => 30.minutes) do url = URI('http://www.xxxxxxxx.com/blog/?json=get_recent_posts') request = Net::HTTP.get(url) ...

Is there a way to modify the value of a constructor key once it has already been defined?

I am currently working on a simple constructor exercise where I need to update a value after the constructor has been created. Even after changing the value to true, the cat is still not making its noise. Challenge parameters The constructor function wi ...

Check if jQuery condition is met for classes that match exactly

The PHP echo statement below contains the code. The brackets are empty, but I can guarantee that the statement inside, which modifies CSS, works - except for one issue. I want it to only target elements with a class attribute equal to "zoom" or "zoom firs ...

JavaScript tip: Improve the way you highlight the current navigation page while scrolling by finding alternative methods to using "scrollY > x"

Currently, my webpage layout is divided into 4 sections - HOME, ABOUT, SKILLS, and CONTACT. Below is the JavaScript code I am using to highlight a specific section on the navigation bar based on the scroll position: let home = document.querySelector(" ...

What is the best way to compare dates in order to obtain the necessary results?

Question : Filter the JSON array to retrieve specific entries 1: All entries with name "Sam". 2: All entries with date "Dec 2019". // JSON Data provided below. var data = [{ "id":"27", "0":{ "name":"Sam", "date":"2021-02-28" ...

What is the best way to trigger an event using vue-chartjs?

I am using vue js to display a graph with chartjs. I have implemented an onClick function on the graph to emit an event in the parent component and retrieve data. However, the event is not working as expected. Can you help me identify the issue? Component ...

Exploring nested optgroup functionality in React.js

Within my code, I am utilizing a nested optgroup: <select> <optgroup label="A"> <optgroup label="B"> <option>C</option> <option>D</option> <option>G</option> </optg ...

Error in TypeScript - Anticipated 1-2 arguments, received either none or multiple. Code Issue TS2556

While working in JavaScript, I had no issues with this code snippet. However, when I attempted to implement it in a TypeScript Project, an error surfaced. The problem seems to revolve around the fetch(...args) function call. const fetcher = (...args) =&g ...

"Step-by-step guide on creating a popup window for editing a row using ng-grid and AngularJS

I recently started diving into angular-js and I'm really impressed with how cool it is. In my search, I came across http://angular-ui.github.io/ng-grid/, which seems to be a user-friendly tool. However, I'm grappling with figuring out how to disp ...