Handling tinyInt booleans with MVC - mysql

I have a mySQL table setup with a column with a datatype of TinyInt(1). This represents a boolean.
0 = false; 1 = true.
I'm also setting up a website to show this information to the company using asp.net and the MVC design. Right now, the table shows the column as:
"Are Records Online"| [next column]
------------------------------------
1 | junk
1 | junk
0 | junk
However, I want the 1's and 0's to display as 'true/false' or 'yes/no'. Basically just something more user-friendly.
How should I do this? With a script on the Viewpage itself or with a foreach loop in the controller such as:
foreach(ListViewModel i in DefaultList)
{
if(i.RecordsOnline == true)
{ //set to 'yes'
}
else if(i.RecordsOnline = false)
{ //set to 'no'
}
}

Just use a simple ternary to print the appropriate bit of text in your view:
#(i.RecordsOnline ? "Yes" : "No")

You can use type ENUM('yes', 'no') instead of TINYINT. The same one byte per value, but more user-friendly.

You could create a DisplayTemplate based on the bool type since you appear to be converting the tinyint to bool in your model.
-- YesNo.cshtml
#model bool
#(Model ? "Yes" : "No")
Place that folder inside of ~/Views/Shared/DisplayTemplates
You can use it like so: (assumes RecordsOnline is part of your model and is a bool)
#Html.DisplayFor(m => m.RecordsOnline, "YesNo")

Related

How to show integer 0 but not empty or NULL in TYPO3 Fluid

In my TYPO3 Fluid template I have a value where I would like to check if its not empty before showing it.
My way now:
<f:if condition="{myvalue}">
<div class="myclass">{myvalue}</div>
</f:if>
This works when I type in the backend a value like "test" or "2", and if I dont type anything it won't show the div tag.
But when I type in the backend "0", the condition is also not true. How can I fix that the integer 0 will be showed, and if its empty (in database NULL) not be showed? (its very common that the value will be 0)
Btw i tried things like:
<f:if condition="{myvalue} !=NULL">
<f:if condition="{myvalue} >= 0">
But then also the empty value's wil be show. If I do
<f:debug>{myvalue}</f:debug>
I get things like:
myvalue = NULL
myvalue = 0
myvalue = "test"
So only the first one must not been shown.
I hope someone can help me, thank you.
There are two solutions first is transient field in your model of bool type which getter just checks if value is not null, but additionally returns true if value is 0 (actually in most languages 0 IS a value)
Second solution is even more universal, it's just writing custom ViewHelper, which will allow uou to check if value is 0 or has value:
<?php
namespace VENDOR\YourExt\ViewHelpers;
class notEmptyOrIsZeroViewHelper extends \TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* #param mixed $value Value to check
*
* #return bool the rendered string
*/
public function render($value) {
return ($value === 0 || $value === '0' || $value) ? true : false;
}
}
So you can later use this as a condition for common <f:if > condition like:
<f:if condition="{yourNameSpace:notEmptyOrIsZero(value: myValue)}">
<f:then>Now it recognizes 0 as a value</f:then>
<f:else>It still DOESN'T recognize 0 as a value</f:else>
</f:if>
I had a similar case, where I wanted to check a fluid variable for 0 or positive integers. A simple >= 0 comparison wouldn't work. In TYPO3 10 LTS I could resolve this problem by doing this:
<f:if condition="{value} === 0 || {value * 1} > 0">
value is zero or positive integer
</f:if>
(Note: this will also allow integer strings, such as "123" or "1st", but not "val3" - basically as you would expect when casting a string as integer in PHP.)
If you just want to check that {value} is not null or empty (but allow zero as a valid value), you can simplify the condition to:
<f:if condition="{value} === 0 || {value}">
value is set and not empty
</f:if>

ActionScript: Specification of the is operator

I am having trouble googling for the expected behavior of the is operator in AS3. What I need to know is what should happen if the left side is null.
I know it is possible to test, and get empirical results, but I need to know what the specification says, and cannot find it anywhere.
You were not looking hard enough.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/operators.html#is
"Evaluates whether an object is compatible with a specific data type, class, or interface."
Because null is kinda SPECIAL CASE and "The Null data type is special in that it is not associated with a class" you will get false while using it with in operator.
The ActionScript 3 Language Specification says the following about the is operator:
The is operator checks to see if the value on the left is a member of
the type on the right. For user-defined types and most built-in types,
is returns true if the value is an instance of a class that is or
derives from the type on the right, otherwise it returns false.
Since null belongs to the special type Null which can't be extended and cannot be used on the right side of the is operator, the is operator will always return false.
| Value | String | Number | int | uint | Boolean | Object |
|-------|--------|--------|-------|-------|---------|--------|
| null | false | false | false | false | false | false |
You can find a bit more about how is operator works from this Adobe article:
It shows this example:
if (xParam is String) { /* do some String things */ }
else if (xParam is Number) { /* do some Number thing */ }
It shows that is operator is for type-checking. Consider var myNumber : dataType = new dataType. Now is the unknown dataType classed as Number?, int?, String? or Bitmap? This method allows you to create function code that anticipates what data format is input and can deal accordingly.
You dont use is to check for a null but alternatively you can use the == equality operator.
if (xParam == null) { /* do IS NULL things */ }
else { /* do some IS NOT NULL thing */ }

Return true when query gives 1

I want to save a true/false in my MySQL database. I'm saving 1/0 in an INT column to do this. When I select it, I get the 1 or 0, but I want it to return true/false to my PHP code, without having to rewrite the database.
Can I use another column type? Should I save it differently?
Update: My question is about not wanting to rewrite the returned value. I'm getting a lot of results from my database. Many of those are true/false, but some are 0s because the price is 0, so I don't want to universally rewrite all 1s and 0s. I also don't want to manually rewrite 10 columns.
To follow up my comment, here's a more detailed response which also covers the PHP side, although this probably belongs on StackOverflow.
I've always just used tinyint, although you can use bool/boolean which are synonyms for tinyint(1)
However as of MySQL 5.0.3 you can use the bit type:
As of MySQL 5.0.3, the BIT data type is used to store bit-field values. A type of BIT(M) enables storage of M-bit values. M can range from 1 to 64.
Next, assuming you have an active column, perhaps to store if a user is active, you could use PHP's automatic type conversion to handle this quite simply.
// Obviously you'd replace this with your database call
$results = [['active' => 1], ['active' => 0]];
foreach($results as $row) {
if ($row['active'] == true) {
echo "true\n";
}
else {
echo "false\n";
}
}
You don't strictly need to do anything.
PHP does not, and can not, use strongly typed variables. So, if you receive an (int) 1 from your query results, you can simply use this 1 as a boolean without rewriting or changing anything.
$intOne = (int) 1; //explicitly treat the variable as an integer
var_dump((bool) $intOne); //treat the variable as a boolean
When used in any boolean context, like if ($variable)... then any of these types will be considered to be false by PHP:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
... And, most importantly;
Every other value is considered TRUE (including any resource).
Source: PHP Manual > Booleans (english)
So while you can change the storage type of your column in mysql, this won't really change the way PHP handles the variable retrieved from your results at all.
Historically, I've always used a column of type TINYINT(1) to store boolean values in mysql, and as Tom Green points out, recent mysql versions provide a new BIT type, which might be appropriate. To the best of my knowledge, mysql does not currently have an actual boolean data type.
You could just as easily use a column of type VARCHAR(1), though, because PHP can and will use any value as a boolean, thanks to the glorious, majestic, and sometimes maddening, PHP Type Juggling.
If you're trying to use the values you're retrieving for boolean logic, just use the values you receive from mysql like booleans and it will work:
if ($valueFromResults) {
//The value was something like true
} else {
//The value was something like false
}
If you're trying to actually echo out the words "true" and "false", then you're probably best served by explicitly echoing the words out yourself, like this;
if ($valueFromResults) {
echo "true";
} else {
echo "false";
}
or, in my preferred shorthand;
echo ($valueFromResults) ? "true" : "false" ;
Update You mentioned in a comment that you want to pass the values through json_encode() and use them in javascript.
JavaScript treats any real value, like int 1, as true and any empty value, like int 0, or an empty string, as false. So if your json_encode() output gets used in actual JavaScript, the int values will still work as boolean values. So the integer values from your database should still work as they are.
Just check that your integer results are encoded as integers by PHP and not as strings - they should be encoded correctly by default - because "0" == true in javascript, but 0 == false.
For a boolean value (true/false), you should use the mySql type bit or tinyint(1).
$boolean = $mysql_data ? true : false;

How can I create a default boolean value for a configuration using BND

I am using BND annotations to assist with creating a configuration managed by OSGI cm.
Here is my simple config
#Meta.AD(required = false, type = Type.Boolean, deflt = "false")
boolean enabled();
I have used the BND configuration annotation library quite a few times, but this is the first time that I would like to use a boolean type.
I have read through this
And it talks about an integer or other alternative number based handling of booleans for convenience. The thing is the deflt method always returns a string value, if my type was an integer I would do "2" (these are parsed). But booleans don't seem to be parsed in the configurable BND code up to this assignment point.
if (resultType == boolean.class || resultType == Boolean.class) {
if ( actualType == boolean.class || actualType == Boolean.class)
return o;
if (Number.class.isAssignableFrom(actualType)) {
double b = ((Number) o).doubleValue();
if (b == 0)
return false;
else
return true;
}
return true;
I would like to further know why this returns true when the deflt value is never even parsed. I expected this to more closely follow the spec and return false, since cm would try to do Boolean.parseFrom, so anything not "true" equal ignore case is false.
All of this isn't a complete failure because if I change the value through cm it works correctly after setting to true, and then false again, but obviously that was just an effort at wondering if it would ever work.
Simply I would like to know if anyone knows how to set a BOOLEAN default value using BND's configuration annotations.
Thanks

BLToolkit MapValue not mapping

We are starting to do a conversion to BL Toolkit but are hitting some issues and not finding answers. One such issue is the inability to get the MapValue attribute on our DTO's properly to map.
Using T4 templates, we generate this (as an example):
[MapField("counterparty_fl")]
[MapValue(true, 'y')]
[MapValue(false, 'n')]
public bool CounterpartyFlag { get; set; } // flag_yn_TY(1)
Our database is Sybase, and the field counterparty_fl is a char(1) that accepts either 'y' or 'n'.
However, when I look at the SQL generated by the following link query, it is writing [counterparty_fl] = 0. What I need is [counterparty_fl] = 'n'
var results = (from i in facade.InputList
where (
i.UserIdentifier == criteria.UserId &&
i.CounterpartyFlag == false &&
i.Name == criteria.Name)
select i);
Has anyone had better luck with MapValue? Any suggestions?
This type of mapping is not supported for linq queries. The problem is that CounterpartyFlag field can be mapped to 'y', 'n' values, but 'false' in your expression can't be.
You can use enum for CounterpartyFlag field type:
public enum
{
[MapValue('y')] Yes,
[MapValue('n')] No
}
This should work.