I am storing data in my contract using a mapping of structs.
For examples sake, say I'm storing employee info (name/address/salary), mapped by their employee ID.
Via a web front-end, I'd like to be able to specify an employee ID, and call a function in my contract (using Web3.JS) that returns the employee info.
How can I access the data if a struct is returned. Is that possible?
Best Answer
Summary
Return the fields of the struct as separate return variables.
Edit: As of 2021, it's possible to return the struct directly. See this answer.
Example
I'm running this code in my local dev blockchain using the following command:
Your web frontend should be able to send transactions to insert the users, and call the functions to get the number of users and and the user info.
Sample Contract
Flatten The Source Code
I use the
stripCrLf
method (from How to load Solidity source file into geth) to transform the formatted source into a single line that can be inserted within thegeth
console. Alternatively, search for a web page that will strip your line breaks from your code. Then assign your code to a JavaScript variable:Insert Contract Into The Blockchain
The compile the code:
Load the code into the blockchain:
Wait for the following message to indicate that the contract has been mined:
Insert Users
And here we are adding 2 users to the contract:
Retrieve Data
Let's get the number of users:
Let's get the information for the first user:
And the second user: