Changeset

11877:593b141ba01c

util.dataforms: Coerce number values for boolean fields Makes more sense than coercing to a string, which would always be truthy.
author Kim Alvefur <zash@zash.se>
date Tue, 26 Oct 2021 15:15:57 +0200
parents 11876:52a1b885044e
children 11878:bf6706057283
files spec/util_dataforms_spec.lua util/dataforms.lua
diffstat 2 files changed, 15 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/spec/util_dataforms_spec.lua	Tue Oct 26 13:35:04 2021 +0200
+++ b/spec/util_dataforms_spec.lua	Tue Oct 26 15:15:57 2021 +0200
@@ -417,6 +417,16 @@
 		end);
 	end);
 
+	describe("number handling", function()
+		it("handles numbers as booleans", function()
+			local f = dataforms.new { { name = "boolean"; type = "boolean" } };
+			local x = f:form({ boolean = 0 });
+			assert.equal("0", x:find "field/value#");
+			x = f:form({ boolean = 1 });
+			assert.equal("1", x:find "field/value#");
+		end);
+	end)
+
 	describe("datatype validation", function ()
 		local f = dataforms.new {
 			{
--- a/util/dataforms.lua	Tue Oct 26 13:35:04 2021 +0200
+++ b/util/dataforms.lua	Tue Oct 26 15:15:57 2021 +0200
@@ -103,8 +103,11 @@
 
 		if value ~= nil then
 			if type(value) == "number" then
-				-- TODO validate that this is ok somehow, eg check field.datatype
-				value = ("%g"):format(value);
+				if field_type == "boolean" then
+					value = value ~= 0;
+				else
+					value = ("%g"):format(value);
+				end
 			end
 			-- Add value, depending on type
 			if field_type == "hidden" then