Preconditions
- It is assumed you already have a multi index table instance defined along with its mandatory primary index, otherwise take a look at the section How to instantiate a multi index table.
To modify data in the multi index table defined in the above tutorial, you will implement an action mod
which it will receive as parameter the user
which is the key of the row you want to modify and the value
param which is the value to update with the row.
- Make use of the multi index table iterator to find out if the data exists
[[eosio::action]] void multi_index_example::mod( name user, uint32_t value ) {
auto itr = testtab.find(user.value);
}
- If the row you want to update is not found, then assert by using the
check
method and yield an error message
[[eosio::action]] void multi_index_example::mod( name user, uint32_t value ) {
auto itr = testtab.find(user.value);
+ check( itr != testtab.end(), "user does not exist in table" );
}
- If the row you want to update is found, the
check
method will do nothing and the iteratoritr
will be pointing at the row which you want to update, so then use the multi indexmodify
method to make the update like below
[[eosio::action]] void multi_index_example::mod( name user, uint32_t value ) {
// check if the user already exists
auto itr = testtab.find(user.value);
check( itr != testtab.end(), "user does not exist in table" );
+ testtab.modify( itr, _self, [&]( auto& row ) {
+ row.secondary = user;
+ row.datum = value;
+ });
}