How to efficiently get the value from form UI built with dynamic InputField
Assign your input in DialogReturn
, e.g. to a variable return
. Apart from from this, and omitting your Dynamic@x
at the end, your code is unchanged:
DynamicForm[row_, col_] :=
DynamicModule[{x = ConstantArray[0, {row, col}], a},
a = {Column[(Row[#] & /@
Table[With[{i = i, j = j},
InputField[Dynamic[x[[i, j]]], Number,
FieldSize -> Tiny]], {i, 1, row}, {j, 1, col}])]};
AppendTo[
a, {CancelButton[], DefaultButton[DialogReturn[return = x]]}];
CreateDialog[
Column[Flatten@{a}, Spacings -> {1, Automatic}, Alignment -> Left],
Modal -> True]]
Now run the dialog and enter your data:
DynamicForm[2, 3];
You can obtain the input from return
:
return
{{1, 2, 3}, {4, 5, 6}}
If you want the evaluation to halt until the Dialog returns you can get your code working very simply:
DynamicForm[row_, col_] :=
DialogInput[{x = ConstantArray[0, {row, col}], a},
Column[Flatten@{{Column[(Row[#] & /@
Table[With[{i = i, j = j},
InputField[Dynamic[x[[i, j]]], Number,
FieldSize -> Tiny]], {i, 1, row}, {j, 1, col}])],
{CancelButton[], DefaultButton[DialogReturn[x]]}}},
Spacings -> {1, Automatic}, Alignment -> Left]]
Note that it's the function DialogInput[] (used here instead of CreateDialog[]) that halts the evaluation, see How to evaluate following inputs only after finishing CreateDialog
This allows you to just use DynamicForm
in place of it's input in equations and such for instance: a=Transpose[DynamicForm[23,34]]
will open a popup and assing a
to the tranposed result upon pressing the OK button.
Update
If you don't want the dialog to return it's value, here is a version that puts the changes into a dynamically updated variable:
setDyn[a_Dynamic, val_] := Extract[a, 1, Function[{w}, w = val, HoldAll]];
DynamicForm[a_Dynamic, row_: 2, col_: 2] :=
CreateDialog[
DynamicModule[{x = ConstantArray[0, {row, col}]},
setDyn[a, x];
Column[{Grid@#1, Row@#2}, Spacings -> {1, Automatic}, Alignment -> Center]
& @@ {
Table[
With[{i = i, j = j},
InputField[
Dynamic[x[[i, j]],
Function[{val, nam}, nam = val; setDyn[a, x], HoldRest]],
Number, FieldSize -> Tiny]],
{i, row}, {j, col}],
{DefaultButton["Close", DialogReturn[]]}
}]
]
Called with DynamicForm[Dynamic[a],4,4]
it will update a
as you change it.