jqgrid search: How to specify search column? - asp.net-mvc

I am using jqgrid on EF4 MVC3 (C#). I based search on this #Oleg 's solution, which works fine and fits for my needs.
I have the following columns defined in my grid:
...
{ name: 'Stato', index: 'StatoTicketID', width: 20, align: 'left', sorttype: 'int', searchoptions: { sopt: ['eq']} },
{ name: 'StatoTicketID', index: 'StatoTicketID', width: 20, align: 'left', sorttype: 'int', hidden: true, searchoptions: { sopt: ['eq']} },
...
As you can see, the column Stato is ordered by the index StatoTicketID (hidden integer field) and ordering works fine.
PROBLEM
When I try to search a value of Stato, the filter is passed on index StatoTicketID as string, while I'd like to search by Stato values. So I get an exception inside the controller which specifies that I cannot convert String type to Int32.
Does exist a way to specify on which column apply search, when index is on a different column, like in my case?
EDIT & WORKAROUND:
For now I solved my problem with the following workaround.
(inside foreach (Rule rule in rules) of FilterObjectSet by Oleg)
....
if (rule.field == "StatoTicketID")
{
rule.field = "StatoTicket.Stato";
propertyInfo = typeof(T).GetProperty("stringfield"); // where stringfield is a text type column of my model
}
I realize very well that is not an elegant solution, I expect a kind response by you, to know how to implement the required behaviour directly from jqGrid, please.
Thanks in advance

It seems to me that you chosen too complex way. I would just send to the client (to the jqGrid) only the Stato and have to StatoTicketID at all. From the design point of your the StatoTicketID is the part of the server implementation and the client should not depend from this.
If you have Unique Constrain (or unique index) on Stato column of the StatoTickets table you would very quickly find the StatoTicketID whenever you as need. So the jqGrid can contain and "know" only about Stato and have no information about the StatoTicketID as the implementation detail.
One more way to solve the problem is the usage of formatter: 'select' in the column Stato. It's important to understand that in the case the mapping between Stato text and the StatoTicketID should be loaded before the grid is created. In the case the Stato column should have the properties like
formatter: 'select', edittype: 'select', editoptions: {value: '12:Stato1;24:Stato2'},
stype: 'select', searchoptions: {value: ':All;12:Stato1;24:Stato2'}
One can't use dataUrl in the case instead of value in the editoptions.
As the result you will be able to fill column Stato with the StatoTicketID data, but the corresponding texts will displayed by jqGrid.
I recommend you better to implement the first way with pure Stato text. All the problems you would be able to solve only on the server part.

Related

Is it possible to use a custom equality operator with Ruby's Set?

I need to diff collections of child objects between 2 parents. Each is about 30,000 objects, and have about a dozen various attributes. Ruby's Set class provides a fast method to subtract one collection from the other, and get the difference. I had been doing this with JSON data, and the whole thing only took a couple seconds.
Now I'm using ActiveRecord to get the datasets. Of course, once the children are unmarshalled from the database, they include attributes :id, :created_at, and :updated_at. Unfortunately, this automatically ruins the comparisons in the diff, because these fields will always be different, and cause the comparison to fail.
Out of the set of attributes, I really only care about :label and :data. That is, I want to compare the objects with the same label between the 2 sets, and see if their data is different.
I can add a custom equivalency operator in my class:
def ==(other)
self.label == other.label && self.data == other.data
end
This works between comparisons of single objects. They are considered equal if (just) their labels and data match. However, this override does not seem to be getting used in this operation, for purposes of determining equivalency:
#diff = (#left.to_set - #right.to_set)
I was hoping that Set would use the object's class' overridden == operator, but this doesn't seem to be the case. My diffs are just all of the one side or the other, depending on the order of the difference. Is there any way to make this happen? (I already also tried overriding .eql?.)
Since this is too long for a comment, here's the SQL implementation of the idea.
WITH
t1 AS (SELECT * FROM tunings WHERE calibration_id = 7960),
t2 AS (SELECT * FROM tunings WHERE calibration_id = 7965)
SELECT t1.label, t1."data", t2."data" FROM t1 FULL OUTER JOIN t2 ON t1.label = t2.label
WHERE t1."data" != t2."data" OR t1."data" IS NULL OR t2."data" IS NULL
Another speed problem I hadn't even brought up yet was that I have to LOOK UP the "right" value, from the corresponding set, when I display the differences in the view, and THAT takes ANOTHER 10 seconds. This is all done in one step.
Because of the CTE's, I'm guessing that I won't be able to put this into ActiveRecord semantics, and I'll just have to pass the raw SQL with seeded values, but I would love to be proven wrong.
Also, I'm still academically interested in original question.
According to Ruby Set class: equality of sets, you need to override both Object#eql? and Object#hash
Here's how you can do it in general Ruby, without having to redefine your classes' identity.
first = [{ id: 1, label: "foo", data: "foo"},
{ id: 2, label: "bar", data: "bar"},
{ id: 3, label: "baz", data: "baz"}]
second = [{ id: 1, label: "foo", data: "foo"},
{ id: 2, label: "baz", data: "baz"},
{ id: 3, label: "quux", data: "quux"}]
first_groups = first.group_by { |e| e.values_at(:label, :data) }
second_groups = second.group_by { |e| e.values_at(:label, :data) }
first_minus_second_keys = first_groups.keys.to_set - second_groups.keys.to_set
first_minus_second = first_minus_second_keys.flat_map { |k| first_groups[k] }
(This is for lists of hashes; for AR classes you'd replace e.values(:label, :data) with [e.label, e.data])
That said, I agree with the Tin Man: it would be way more performant to do this at the database level.

Kendo grid MVC5,count of no of records is not showing

Using kendo grid for displaying the data,instead of the count it showing NAN of NAN items. How can I solve this?
I solved this issue by using this code in schema Thankss....
schema: {
data: "Data",
total: function (response) {
return response.Total;
},
There are 2 options, the first you already found it: define a function that computes total. The second, in your case, it's much simpler since you only need to say which fields includes the total.
Something like:
schema: {
data: "Data",
total: "Total"
}
For more information check the manual here.

Tablesorter: set a widget option to true for one column and false for another.

I'm trying to figure out how to set filter_startsWith: true for one column, and false for another column. In the case of one of my tables, I have an int column and a varchar column. The int column needs to be sorted with filter_startsWith: true. The varchar column needs filter_startsWith: false. Any ideas?
Currently, the filter_startsWith option applies to all columns. It would not be too difficult to alter the plugin code to make it work per column; I will add this to my "to do" list.
If you want to set a default filter which always applies to a column, and prevents other filter types from working properly, then you can set the filter_defaultFilter option to use regex to target a specific column (demo):
$(function () {
$('table').tablesorter({
theme: 'blue',
widgets: ['zebra', 'filter'],
widgetOptions: {
filter_defaultFilter : {
2: '/^{query}/'
}
}
});
});

Cast Varchar as Integer in propel for addAscendingOrderByColumn

I have a method in order to get data out of a database for a propel-based symfony-1.1 project.
Now the use-case arrived to store an integer into a varchar field, which results in a wrong order, e.g. {1, 17, 5}, and not the numeric one I was expecting, i.e. {1, 5, 17}.
I know that one way would be to redesign my schema.yml, but this is not an option. I was wondering if there is a way to cast said varchar field as an integer without harming the propel-approach.
This is the sorting function:
public static function getFooData($column = 'FooPeer::ID', $orderBy = 'asc') {
//FIXME: Sort varchar fields as integer, needed for FooPeer::REQUESTS
$c = new Criteria();
if ($orderBy == 'asc') {
$c->addAscendingOrderByColumn($column);
} else {
$c->addDescendingOrderByColumn($column);
}
return FooPeer::doSelect($c);
}
What about:
$c->addAscendingOrderByColumn('CAST('.$column.' AS UNSIGNED)');
Just for interest, you could also have written a view for this, and build your model on top of the view rather than the table. Assuming you're writing to the table with Propel, this solution requires the platform to support writable views (I'm not sure they all do, but perhaps that assumption is out of date).
This is often a good/quick technique where you're not sure how to do something in Propel, or where it is really awkward. It's saved me a few times, even though it's not every purist's cup of tea.

Difference between string and text in rails?

I'm making a new web app using Rails, and was wondering, what's the difference between string and text? And when should each be used?
The difference relies in how the symbol is converted into its respective column type in query language.
with MySQL :string is mapped to VARCHAR(255)
https://edgeguides.rubyonrails.org/active_record_migrations.html
:string | VARCHAR | :limit => 1 to 255 (default = 255)
:text | TINYTEXT, TEXT, MEDIUMTEXT, or LONGTEXT2 | :limit => 1 to 4294967296 (default = 65536)
Reference:
https://hub.packtpub.com/working-rails-activerecord-migrations-models-scaffolding-and-database-completion/
When should each be used?
As a general rule of thumb, use :string for short text input (username, email, password, titles, etc.) and use :text for longer expected input such as descriptions, comment content, etc.
If you are using postgres use text wherever you can, unless you have a size constraint since there is no performance penalty for text vs varchar
There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead
PostsgreSQL manual
String translates to "Varchar" in your database, while text translates to "text". A varchar can contain far less items, a text can be of (almost) any length.
For an in-depth analysis with good references check http://www.pythian.com/news/7129/text-vs-varchar/
Edit: Some database engines can load varchar in one go, but store text (and blob) outside of the table. A SELECT name, amount FROM products could, be a lot slower when using text for name than when you use varchar. And since Rails, by default loads records with SELECT * FROM... your text-columns will be loaded. This will probably never be a real problem in your or my app, though (Premature optimization is ...). But knowing that text is not always "free" is good to know.
String if the size is fixed and small and text if it is variable and big.
This is kind of important because text is way bigger than strings. It contains a lot more kilobytes.
So for small fields always use string(varchar). Fields like. first_name, login, email, subject (of a article or post)
and example of texts: content/body of a post or article. fields for paragraphs etc
String size 1 to 255 (default = 255)
Text size 1 to 4294967296 (default = 65536)2
As explained above not just the db datatype it will also affect the view that will be generated if you are scaffolding.
string will generate a text_field text will generate a text_area
Use string for shorter field, like names, address, phone, company
Use Text for larger content, comments, content, paragraphs.
My general rule, if it's something that is more than one line, I typically go for text, if it's a short 2-6 words, I go for string.
The official rule is 255 for a string. So, if your string is more than 255 characters, go for text.
The accepted answer is awesome, it properly explains the difference between string vs text (mostly the limit size in the database, but there are a few other gotchas), but I wanted to point out a small issue that got me through it as that answer didn't completely do it for me.
The max size :limit => 1 to 4294967296 didn't work exactly as put, I needed to go -1 from that max size. I'm storing large JSON blobs and they might be crazy huge sometimes.
Here's my migration with the larger value in place with the value MySQL doesn't complain about.
Note the 5 at the end of the limit instead of 6
class ChangeUserSyncRecordDetailsToText < ActiveRecord::Migration[5.1]
def up
change_column :user_sync_records, :details, :text, :limit => 4294967295
end
def down
change_column :user_sync_records, :details, :string, :limit => 1000
end
end
If you are using oracle... STRING will be created as VARCHAR(255) column and TEXT, as a CLOB.
NATIVE_DATABASE_TYPES = {
primary_key: "NUMBER(38) NOT NULL PRIMARY KEY",
string: { name: "VARCHAR2", limit: 255 },
text: { name: "CLOB" },
ntext: { name: "NCLOB" },
integer: { name: "NUMBER", limit: 38 },
float: { name: "BINARY_FLOAT" },
decimal: { name: "DECIMAL" },
datetime: { name: "TIMESTAMP" },
timestamp: { name: "TIMESTAMP" },
timestamptz: { name: "TIMESTAMP WITH TIME ZONE" },
timestampltz: { name: "TIMESTAMP WITH LOCAL TIME ZONE" },
time: { name: "TIMESTAMP" },
date: { name: "DATE" },
binary: { name: "BLOB" },
boolean: { name: "NUMBER", limit: 1 },
raw: { name: "RAW", limit: 2000 },
bigint: { name: "NUMBER", limit: 19 }
}
https://github.com/rsim/oracle-enhanced/blob/master/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb
If the attribute is matching f.text_field in form use string, if it is matching f.text_area use text.

Resources