How to acquire sqlform's field dynamically in web2py - asp.net-mvc

my table:
db.define_table('problem',
Field('title','string',unique=True,length=255),
Field('description','text',notnull=False,default=''),
Field('in_date','datetime',notnull=False,default=request.now),
Field('input','text',notnull=False,default=''),
Field('result','text',notnull=False,default=''),
Field('defresult','text',notnull=False),
Field('submit','integer',notnull=False,default=0),
Field('solved','integer',notnull=False,default=0),
Field('pass_rate','decimal(2,2)',notnull=True,default =0.00),
format = '%(title)s')
Insert a record into problem table by sqlform,how to acquire the result field of problem in sqlform dynamically.
def test():
user_id=_get_user_id(auth)
id=request.args(0,cast=int)
for row in db(db.belongs.id==id).select():
taskid=row.task_id
problemid=row.problem_id
record=db.problem(problemid) or redirect(URL('index'))
fields=['title','description','input','result']
form=SQLFORM(db.problem,record,readonly=False,fields=fields)
if form.process().accepted:
db(db.problem.id==problemid).update(submit=db.problem.submit+1)
if(form.vars.result==db.problem.defresult):
The last line I want to judge if the result field is equal to the defresult field.
The form.vars.result seems not change even I input another value into sqlform and the values insert before have fill the sqlform after I reloading the page. how to clear the sqlform? Thanks!

form.vars.result does contain the new value. The problem is that in form.vars.result==db.problem.defresult, you are comparing that value to a Field object rather than to the actual value from the record. Earlier, you have:
record=db.problem(problemid)
So, your equality test should be:
if form.vars.result == record.defresult:

Related

Unable to save an Entry because matrix field is invalid - Craft CMS 2

I'm trying to save an Entry but Craft errors because of an invalid matrix field. The Entry includes a matrix field but I haven't changed it. I'm trying to edit another field. When I save the entry manually from the admin panel, it saves fine without any errors.
I have researched this problem online and a lot of people were recommending that I provide the matrix's ids when saving the entry. However, even then, I still get an error.
In the code below you'll see that I'm trying to save 3 fields:
Cover Image
Language
Tracks
Each of these fields required me to manually save them because they are relations. That's OK, however, as mentioned earlier, the matrix field (named tracks) errors.
Here's my code below
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = "programmes";
$entry = $criteria->first([
"slug" => $programme["slug"]
]);
if ($entry) {
// Update Entry attributes
$entry->getContent()->coverImage = $entry->coverImage->ids();
$entry->getContent()->tracks = $entry->tracks->ids();
$entry->getContent()->language = $entry->language->ids();
// Save Entry
if (!craft()->entries->saveEntry($entry)) {
return $entry->getErrors();
}
}
The error that comes back is the following
Argument 1 passed to Craft\MatrixService::validateBlock() must be an instance of Craft\MatrixBlockModel, string given, called in craft/app/fieldtypes/MatrixFieldType.php on line 451
Including the matrices themselves and not their ids has worked.
$entry->getContent()->tracks = $entry->tracks->all();

Telegraf Processor value to fieldname

I have points from my Input like these two:
http,Location=Foo Key="Humidity",Value=68 1659704523000000000
http,Location=Foo Key="Temperature",Value=24,1 1659704523000000000
But I have to store them like these:
http,Location=Foo Humidity=68 1659704523000000000
http,Location=Foo Temperature=24,1 1659704523000000000
I saw almost all of Processor plugin docs, but I still not sure it is possible to use field value as a field name. Isn't it?
I still not sure it is possible to use field value as a field name. Isn't it?
Yep! The starlark processor will do this. The 'pivot' example is what you are after.
The following will create a new field based on the values of Key and Value and then remove the original values:
[[processors.starlark]]
source = '''
def apply(metric):
metric.fields[str(metric.fields['Key'])] = metric.fields['Value']
metric.fields.pop('Key',None)
metric.fields.pop('Value',None)
return metric
'''

When I run sql query there is no alert

This code insert the record into the basetable without alert.
CurrentDb.Execute _
"INSERT INTO basetable(clName,clId,clGender) VALUES('test','123','');"
I expected this code should pop alert up because the clGender field set to be "required", but no alert. Could you please tell me where I was wrong.
You can use:
DoCmd.RunSQL " Insert ... "
though that may be too much.
The reason you didn't get an alert is because you supplied a value for clGender. In table design view there are two relevant properties: Required and Allow zero length. Your clGender field has both of these set to true. The Required setting means that you can't save the record with this field as Null but in your insert statement you haven't specified Null, you've specified an empty string, which is allowed by the Allow zero length setting.
[EDIT]
Sorry, just realised what's going on. The Execute method doesn't give you any feedback directly. However you can use the RecordsAffected property to see if it did what you expected.
Dim db As DAO.Database
Set db = CurrentDb()
db.Execute "INSERT INTO basetable(clName,clId,clGender) VALUES('test','123','')"
If db.RecordsAffected = 0 Then
MsgBox "Insert failed"
End If
Set db = Nothing

Could not parse sql timestamp string error message

At the point of posting a record to a database table I get the following error:
Could not parse sql timestamp string.
At the click of a button my code does the following:
qry1.Open;
qry1.Insert;
qry1.FieldByName('files_uploaded').asdatetime := qry2.FieldByName('files_uploaded').asdatetime;
qry1.Post;
qry1.Close;
The datatype for the field in the database table is timestamp.
Example of the data in the field : 2014-04-23T14:48:40.816+01:00.
I'm not entirely sure what I'm doing wrong or unless its something to do with the field data.
Any help would be appreciated.
Please try this code:
qry1.Open;
qry1.Insert;
qry1.FieldByName('files_uploaded').AsSQLTimeStamp :=qry2.FieldByName('files_uploaded').AsSQLTimeStamp;
qry1.Post;
qry1.Close;
Try setting ".Value" instead of defining the Data Type. When you use .Value the dataset will convert everything that is necessary.
qry1.Open;
qry1.Insert;
qry1.FieldByName('files_uploaded').Value :=qry2.FieldByName('files_uploaded').Value;
qry1.Post;
qry1.Close;

grails and double values saving

In my Grails project I have a Domain Class with a double field as follows:
double totalAmount;
the value of this field are calculated by a sum done after selecting values in a multiple select. the function for sum values is in the controller, as follows:
def sumReceiptItems(){
params.list("receiptItemsSelected").each {i-> println("element "+i)}
def appList = params.list("receiptItemsSelected")
List<ReceiptItem> allSelectedIds = ReceiptItem.findAllByIdInList(params.receiptItemsSelected.split(',')*.toLong())
def totalAmount = allSelectedIds.amount.sum()
println("totalAmount is = "+totalAmount)
render totalAmount as Double
}
the function works well. After function calling, to update the field in GSP page, I use a javascript method as follows:
function updateTotalAmount(name, data, presentNullAsThis){
if(data !=null)
document.getElementById(name).value= data;
else
document.getElementById(name).value=presentNullAsThis;
}
The javascript works and I see the updating of the field at runtime, but the double value is shown with a dot, and not with comma to separate decimal values. Infact, after clicking by save button to save the instance of the domain class, the value is saved without separating decimals, for example:
if the value into the fiels is 10.50 it is stored as 1050
In this discussion how can save a double type correctly in grails? I've read a similar problem, but solution is not good for my issue.
Anybody can help me?
Values with decimal separator depends on the current Locale of the user. Normally you use g.formatNumber in the view to display correctly the value.
You can check this topic on how to discover the decimal separator for a Locale.
To get the user's Locale use:
Locale locale = RequestContextUtils.getLocale(request)
I have solved the problem in this way:
I've updated my Javascript as follows:
function updateTotalAmount(name, data, presentNullAsThis)
{
var data2 = data.toString().replace(/\./g, ',');
if(data2 != null) document.getElementById(name).value= data2;
else document.getElementById(name).value= presentNullAsThis;
}
I've removed "type="number"" in the gsp related field

Resources