Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing booleans in hidden fields

Is there a recommended way to represent booleans in HTML form hidden fields?

Is it usually a matter of existence, or should one use 1/0 or "true"/"false" strings?

like image 869
Yarin Avatar asked Sep 22 '13 18:09

Yarin


2 Answers

Would be useful if you are using PHP:

test.php?test=false (constructed with http_build_query( array( 'test'=>'false' ) )):

var_dump( $_REQUEST['test'] ); //string(5) "false"

var_dump( (bool)$_REQUEST['test'] ); //bool(true)

var_dump( $_REQUEST['test'] == FALSE ); //bool(false)

var_dump( $_REQUEST['test'] == "false" ); //bool(true)

--

test.php?test=0 (constructed with http_build_query( array( 'test'=>FALSE ) )):

var_dump( $_REQUEST['test'] ); //string(1) "0"

var_dump( (bool)$_REQUEST['test'] ); //bool(false)

var_dump( $_REQUEST['test'] == FALSE ); //bool(true)

like image 158
MikeStack Avatar answered Sep 29 '22 13:09

MikeStack


That logic can be implemented with monkey patching of variable according to it's string value. In that case recommended way of identifying Boolean value depends on how that values are treated by server side. See monkey patching example in Ruby.

However you can avoid monkey patching with approach below:

Most likely all servers would work well with 'true' value to represent True (actually there are no matter as long as you work directly with string, but for convention it's clearly understandable) and empty string'' to represent False (because empty string '' would be treated as false in most cases, to do that you can define input[type=hidden] as placeholder of hidden value and assign corresponding value.

To define hidden input with Falsy value you have to set value attribute to empty string '', all other values would be treated as Truly.

<input type="hidden" name="is-truly" value="">

In that way most likely request.POST['is-truly'] value on the server would be treated as False ( because empty string '' is Falsy, but you have to double check that on server side)

NOTE: It's not recommended to use eval to verify variable type.

like image 32
Andriy Ivaneyko Avatar answered Sep 29 '22 13:09

Andriy Ivaneyko