Question: How can I use the Material-Tables "lookup" function to try and prefill the row based on what's chosen.
I've got an array that contains all important values, and if I were to use the lookup value to choose someone, I want that to then "prefill" the row using the data based on the array.
Relevant code:
var arrayLookupValues = [
{ name: "John Adams", birthYear: "1826", birthCity: "Massachusetts" },
{ name: "Thomas Jefferson", birthYear: "1743", birthCity: "Virginia" },
{ name: "George Washington", birthYear: "", birthCity: "" }
];
columns: [
{
title: "Name",
field: "name",
lookup: {
1: "John Adams",
2: "Thomas Jefferson",
3: "George Washington"
}
},
{ title: "Birth Year", field: "birthYear" },
{
title: "Birth Place",
field: "birthCity"
}
],
Code Sandbox:
https://codesandbox.io/s/material-demo-0q5zo?fontsize=14&hidenavigation=1&theme=dark
An example of what I want to try and do:
Then when John Adams is selected, the Birth Year and Birth Place are filled (as an example below).
If George Washington were selected, since the "arrayLookupValues" does not contain a birthYear or birthCity for him, I would expect it to just leave the fields blank.
I've attempted an onClick in onRowAdd (essentially setting the newData to be the specific array value I want). The issue is once you click the "tick", then the data is prefilled only after clicking it and not before.
I want someone to be able to click the "plus" button then choose an option from the lookup and then prefill the row before clicking the tick to save into the "data" array.
You can simply override the editComponent of the field to return the matching data for the selected value:
editComponent: ({ onChange, onRowDataChange, ...props }) => {
const onCustomChange = value => {
const lookup = props.columnDef.lookup;
const matchingValue = jsonContainingValues.find(
val => val.name === lookup[value]
);
const newValue = { ...matchingValue };
newValue.name = value;
onRowDataChange(newValue);
};
return <MTableEditField onChange={onCustomChange} {...props} />;
},
By updating the data with onRowDataChange
, you can override the whole object instead of that the current field.
Here is a fork of your sandbox.